0

I've read dozens of posts about this and tried as many solutions, but I can't seem to get anything to work. I am populating a listview from a JSON response, which includes numerous (sometimes over 100) rows. Each row has an associated (and different) image.

In a performance test, when I didn't download/display the images, 134 rows from a JSON response were processed and displayed in less than 2 seconds. Awesome! However, when I turned the image downloads/displays back on, it took about 10 years.

It's painfully obvious that I need to use a background thread to download the images, but every solution I've found online has been unsuccessful (assuming some error on my part at this point).

I think I have an idea where I need to process the images in the background, but I'm not exactly sure how to go about setting it up.

Right now, the images (along with all the other data) is loaded into an array. Each image gets downloaded inline right now, hence the incredible performance nightmare.

Here is some code excerpts from my main activity class...

InputStream is = null;
        //http post
        try{
            postQuery = "my api path";
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(postQuery);
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

      //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
        }catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
        }

        m_bottles = new ArrayList<Bottles>();
        this.m_adapter = new BottleAdapter(this, R.layout.bottlelistimagelayout, m_bottles);
                setListAdapter(this.m_adapter);

        viewBottles = new Runnable(){
            public void run() {
                getBottles();
            }
        };
    Thread thread =  new Thread(null, viewBottles, "MagentoBackground");
        thread.start();
        m_ProgressDialog = ProgressDialog.show(SpiritsBottles.this,    
              "Please wait...", "Retrieving data ...", true);
public class Bottle{
        public String name_abbrArray;
    }
    private void getBottles(){
        try{
            JSONObject row = new JSONObject(result);
            array = row.getJSONArray("bottles");
            m_bottles = new ArrayList<Bottles>();
            for(int i=0;i<array.length();i++){
                row = array.getJSONObject(i);
                bottleID = row.getInt("id");
                name_abbr = row.getString("name_abbr");
                bottlePicture = row.getString("image");
                Bottles o = new Bottles();
                o.setbottleID(bottleID);
                o.setname_abbr(name_abbr);
                o.setbottlePicture(bottlePicture);
                m_bottles.add(o);
                Log.i("ARRAY", "" + m_bottles.size() + " - " + i + " / " + array.length()+"m_bottles size = "+m_bottles.size());
            }
          } catch (Exception e) {
            Log.e("PROC - bottleid = "+bottleNamesMap.get("bottlePicture2"), e.getMessage());
          }
          runOnUiThread(returnRes);
      }

    private Runnable returnRes = new Runnable() {

    public void run() {
        if(m_bottles != null && m_bottles.size() > 0){
            m_adapter.notifyDataSetChanged();
            for(int i=0;i<m_bottles.size();i++)
            m_adapter.add(m_bottles.get(i));
        }
        m_ProgressDialog.dismiss();
        m_adapter.notifyDataSetChanged();
        }
      };
private class BottleAdapter extends ArrayAdapter<Bottles> {

        private ArrayList<Bottles> items;

        public BottleAdapter(Context context, int textViewResourceId, ArrayList<Bottles> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.bottlelistimagelayout, null);
                }
                Bottles o = items.get(position);
                if (o != null) {
                        final TextView bottlenametv = (TextView) v.findViewById(R.id.bottlename);
                        final ImageView iv = (ImageView) v.findViewById(R.id.icon);
                        if (bottlenametv != null) {
                            bottlenametv.setText(o.getname_abbr());
                            bottlenametv.setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    Intent intent = new Intent(getApplicationContext(), SingleBottleDisplay.class);
                                    intent.putExtra("name", bottlenametv.getText());
                                    startActivityForResult(intent,0);
                                }
                            });
                        }
                        if(iv != null){
                            iv.setImageBitmap(o.getbottlePicture());
                            iv.setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    Intent intent = new Intent(getApplicationContext(), SingleBottleDisplay.class);
                                    intent.putExtra("name", bottlenametv.getText());
                                    startActivityForResult(intent,0);
                                }
                            });
                        }
                }
                return v;
        }
    }

Here is my bottles class where I am currently downloading each row's image inline (which is my performance problem).

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class Bottles {

    private int bottleID;
    private String name_abbr;
    private Bitmap bottlePicture;

    public int getbottleID() {
        return bottleID;
    }
    public void setbottleID(Integer bottleID) {
        this.bottleID = bottleID;
    }
    public String getname_abbr() {
        return name_abbr;
    }
    public void setname_abbr(String name_abbr) {
        this.name_abbr = name_abbr;
    }
    public void setbottlePicture(String bottlePicture) throws MalformedURLException, IOException {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize=6;
        Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(bottlePicture).getContent(), null, options);
        this.bottlePicture = bitmap;
    }
    public Bitmap getbottlePicture() {
        return bottlePicture;
    }
}

I'm really, really hoping someone can help me out with this as I'm at the end of my rope and almost out of coffee... :)

3 Answers 3

2

I think it would be best if you were to put the downloading of the image in the second snippet into a thread.

See http://developer.android.com/resources/articles/painless-threading.html for more detail on threading, but basically you would create a method like 'private Bitmap downloadImage(url) {...}' inside which would be something like this:

new Thread(new Runnable() {
public void run() {
  final Bitmap b = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
  mImageView.post(new Runnable() {
    public void run() {
      return b;
    }
  });
}
}).start();

That code is untested, but it should work :)

0
1

This is a classic issue with listviews that need to load images. The accepted pattern is "lazy loading" the images, which essentially means that in getView (in your adapter) you start an AsyncTask which loads the image. The view is returned and the UI thread continues, so you don't have a performance issue. Later, the AsyncTask completes, and it adds the downloaded image to the view that was returned previously.

Googling "lazy load listview" will return a ton of results.

This is also a better solution because all of the images aren't loaded at once, which can cause out-of-memory issues when your list becomes too large.

An additional performance gain can be realized by making a cache of images, so that you don't need to reload the image if it's in the cache. This may be overkill but a HashMap of imagename => SoftReference(Bitmap) can provide this functionality. If the key exists in the cache, and the SoftReference is still valid, use the Bitmap there; otherwise use the async task to reload the image (and save it to the cache...)

Finally -- there is an interesting wrinkle to all this. As you can see, getView() sometimes will recycle a view -- that is, when a particular list item scrolls out of the display, it is sometimes reused (to avoid the cost of recreating a new view). So, an async task may be running which references a view which is currently being used for some other new object. the lazy load pattern generally sets the tag on the view, and if that tag is unchanged when the async task returns, it goes ahead and adds the image to the view. Otherwise, the implication is that the image is no longer needed.

1

Thanks very much for the info Todd and Elijah. What I ended up doing is using the UniversalImageLoader library provided by nostra13 here.

My implementation of the code was in getView() of the first snippet above and ended up looking like this...

final ImageView iv = (ImageView) v.findViewById(R.id.icon);

if(iv != null){
         //iv.setImageBitmap(o.getbottlePicture());
         ImageLoader imageLoader = ImageLoader.getInstance();
         imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));
         imageLoader.displayImage(o.getbottlePicture(), iv);
         iv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), SingleBottleDisplay.class);
                intent.putExtra("name", bottlenametv.getText());
                startActivityForResult(intent,0);
            }
         });
}

It works perfectly! Many thanks to nostra13 for the fantastic library!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.