Search code examples
androidandroid-listviewandroid-galleryandroid-lazyloading

Async Loading images in gallery view in Listview from SDCard


I am trying to display the images in galleryViews which are in ListView. I am downloading images from server to SDCard and then displaying it, first I am checking images in cache if image is not there then I am loading it from sdcard.

when the user starts the app for the first time I am downloading the images from server and saving them to sdcard in the mean time iam showing the activity with text only

I want if the image is not there in sdcard the after downloading the image it should display the image as soon as the image is download here is what I am doing.

public class AsyncImageLoader {
   private boolean isImageView;
   private final LinkedHashMap<String, Bitmap> cache = 
      new LinkedHashMap<String, Bitmap>(60, (float) 1.0, true);


Handler handler = new Handler() {

@Override
public void handleMessage(Message msg) {
  super.handleMessage(msg);

  LoadImageFromSdCard loadImage = (LoadImageFromSdCard) msg.obj;
  if (isImageView) {
    loadImage.imageView.setImage(loadImage.bmp);
  } else {
     Thread thread = new Thread(new LoadImageFromSdCard(loadImage.uri,  loadImage.imageView));
     try {
         Log.i("AsyncImageLoader", "SECOND THREAD STARTED");
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
     thread.start();
   }
  }
};


public Bitmap loadImage(String uri,
  ImageTextComboControl imageView) {
if (cache.containsKey(uri)) {
  return cache.get(uri);
} else {
  handler.post(new LoadImageFromSdCard(uri, imageView));
}

return null;
}

private class LoadImageFromSdCard implements Runnable {

 String uri;    
 ImageTextComboControl imageView;
 ImageView image;
 Bitmap bmp = null;

 public LoadImageFromSdCard(String uri, ImageTextComboControl imageView) {
  this.uri = uri;
  this.imageView = imageView;
 }

public void run() {
  FileInputStream fis;
  try {
    fis = new FileInputStream(new File(uri));
  } catch (FileNotFoundException e) {
    e.printStackTrace();
    return;
  }
  bmp = BitmapFactory.decodeStream(fis);
  if (imageView != null) {
    isImageView = true;
    cache.put(uri, bmp);
    Message message = new Message();
    message.obj = this;
    handler.sendMessage(message);
  } 

  }
 }
}

Thanx


Solution

  • I solved my problem using onContentChanged() method in adapter. I am saving images to sdCard and getting the sdCard path saving it into sqlite database so when ever the data is changing in sqlite database onContentChanged method is called because I am using Cursor Adapter.