1

I have an Android Gallery ImageAdapter implementation for getView() that looks as follows:

public View getView(int arg0, View arg1, ViewGroup arg2) {
    String strURL = "http://app1.exactdev.co.za/android/celebs/celeb" + (arg0+1) + ".jpg";      
    Bitmap bm = RemoteBitMapHelper.getRemoteBitMap(strURL); //synchronous request               

    ImageView i = new ImageView(ctx);       
    i.setImageBitmap(bm); 
    return i;
}

How can I make getView do its job asynchronously?

n4rzul
  • 4,059
  • 7
  • 45
  • 64

1 Answers1

1

The simple answer is you could put it inside an AsyncTask. Something like the following (untested)

public View getView(int arg0, View arg1, ViewGroup arg2) {

    final ImageView i = new ImageView(ctx);
    String url = "http://app1.exactdev.co.za/android/celebs/celeb" + (arg0 + 1) + ".jpg";

    new AsyncTask<String, Void, Bitmap>() {

        @Override
        protected Bitmap doInBackground(String... urls) {
            return RemoteBitMapHelper.getRemoteBitMap(urls[0]);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                i.setImageBitmap(result);
            }
        }

    }.execute(url);

    return i;
}
sksamuel
  • 16,154
  • 8
  • 60
  • 108
  • Hasn't really improved my galleries performance like I hoped, but this works like I expected it to, like a charm!. Quickly implemented a simple public static Map picsMap = new HashMap() to cache images already downloaded and performance is up by like 300%. Thanks a lot! – n4rzul Jun 08 '11 at 12:04
  • I'm slowly learning exactly how everything groks together with the Android api. This answer has helped a lot. – n4rzul Jun 08 '11 at 12:07
  • getView can be called many times for the same item: http://stackoverflow.com/questions/2618272/custom-listview-adapter-getview-method-being-called-multiple-times-and-in-no-coh – Sebastian Roth Sep 27 '11 at 04:39