Skip to content

Instantly share code, notes, and snippets.

@KamilLelonek
Created August 2, 2013 11:58
Show Gist options
  • Save KamilLelonek/6139351 to your computer and use it in GitHub Desktop.
Save KamilLelonek/6139351 to your computer and use it in GitHub Desktop.
package pwr.rss.reader.utils;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
public class BitmapDownloader extends AsyncTask<String, Void, Bitmap> {
private final static String TAG = BitmapDownloader.class.getSimpleName();
private long id;
private ImageView imageView;
private Drawable placeholder;
public BitmapDownloader(long id, ImageView imageView) {
this.id = id;
this.imageView = imageView;
this.placeholder = getResources().getDrawable(android.R.drawable.gallery_thumb);
setImageId(id);
}
private Resources getResources() {
return imageView.getContext().getResources();
}
private void setImageId(long id) {
this.imageView.setTag(id);
}
@Override
protected void onPreExecute() {
imageView.setImageDrawable(placeholder);
}
@Override
protected Bitmap doInBackground(String... inputUrls) {
try {
return getBitmapFromUrl(inputUrls[0]);
}
catch (Exception e) {
logErrorIfNotNullPointerException(e);
return null;
}
}
public static Bitmap getBitmapFromUrl(String inputUrl) throws MalformedURLException, IOException {
URL url = new URL(inputUrl);
InputStream stream = url.openStream();
return BitmapFactory.decodeStream(stream);
}
private void logErrorIfNotNullPointerException(Exception e) {
if (e != null) {
Log.e(TAG, e.getMessage());
}
}
@Override
protected void onPostExecute(Bitmap result) {
if (resultExists(result)) {
long forId = getImageId();
if (isIdForImage(forId) && imageViewExists()) {
this.imageView.setImageBitmap(result);
}
}
}
private Long getImageId() {
return (Long) imageView.getTag();
}
private boolean isIdForImage(long forId) {
return forId == this.id;
}
private boolean resultExists(Bitmap result) {
return result != null;
}
private boolean imageViewExists() {
return imageView != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment