Skip to content

Instantly share code, notes, and snippets.

@mancdevcarl
Last active December 18, 2015 07:58
Show Gist options
  • Save mancdevcarl/5750508 to your computer and use it in GitHub Desktop.
Save mancdevcarl/5750508 to your computer and use it in GitHub Desktop.
HttpRequest, extend Async, Interface callback to ImageView
import com.example.streetview.HttpRequest.NetworkListener;
public class MainActivity extends Activity implements NetworkListener {
ImageView iv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.img);
URI uri = null;
try {
uri = new URI("http://maps.googleapis.com/maps/api/streetview?size=400x500&location=40.720032,%20-73.988354&sensor=false&heading=1.78");
} catch (URISyntaxException e) {
e.printStackTrace();
}
String req = uri.toASCIIString();
HttpRequest request = new HttpRequest(this, iv);
request.execute(req);
}
public void networkRequestCompleted(Bitmap streetViewPic) {
if (streetViewPic == null) {
return;
}
iv.setImageBitmap(streetViewPic);
}
}
public class HttpRequest extends AsyncTask<String, String, Bitmap> {
public interface NetworkListener {
void networkRequestCompleted(Bitmap streetViewPic);
}
private NetworkListener _listener;
ImageView iv;
Bitmap bitmap;
public HttpRequest(NetworkListener listenerParam, ImageView ivParam) {
_listener = listenerParam;
iv = ivParam;
}
@Override
protected Bitmap doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
bitmap = BitmapFactory.decodeStream(response.getEntity()
.getContent());
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.d("error:", e.getMessage());
} catch (IOException e) {
Log.d("error:", e.getMessage());
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (_listener != null) {
_listener.networkRequestCompleted(result);
iv.setImageBitmap(bitmap);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment