Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android class, downloads an image from an url and sets it in the an ImageView.
/*
* Instantiate this class and use the method "execute", just give the image url and the ImageView where you want to set it.
* Notice that you may only use the method once, you need to have one object per image request.
* You don't have to worry about threads or blocking your app, this is handled with the AsyncTask class.
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
public class ImageRequester extends AsyncTask<String, Void, Bitmap> {
private ImageView view;
public void execute (String urlString, ImageView v) {
view = v;
this.execute(urlString);
}
protected Bitmap doInBackground(String... urls) {
return loadImageFromSite(urls[0]);
}
protected void onPostExecute(Bitmap result) {
view.setImageBitmap(result);
}
private Bitmap loadImageFromSite (String urlString) {
URL url = null;
try {
url= new URL(urlString);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
try {
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream inputstream = conn.getInputStream();
return BitmapFactory.decodeStream(inputstream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.