Skip to content

Instantly share code, notes, and snippets.

@digidigo
Created January 28, 2011 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digidigo/801114 to your computer and use it in GitHub Desktop.
Save digidigo/801114 to your computer and use it in GitHub Desktop.
Android ImageView loaded from the Web
import java.io.InputStream;
import java.net.URL;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;
public class WebImageView extends ImageView {
public WebImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public WebImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WebImageView(Context context) {
super(context);
}
private DownloadImageTask task;
public void setUrl(String url) {
synchronized (this) {
if (task != null)
task.cancel(true);
task = (new DownloadImageTask());
task.execute(url);
}
}
private class DownloadImageTask extends
AsyncTask<String, Integer, Drawable> {
private Drawable loadImageFromNetwork(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
protected Drawable doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Drawable result) {
setImageDrawable(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment