Srikanth
Srikanth

Reputation: 164

Loading images from server to Android custom listview when scrolling down the listview

I have a custom listview that contains images and text from the server. If server returns 500+ sets of data I can render all the data to my listview but it will take lots of time to load

Instead I should render the data when list is scrolled down. For this I was return the some code to load the images but still I was not satisfied with this code. I am loading the images from the getView() method by calling manager.fetchBitMapThread(data.getImgUrl(),iv) (ImageLoaderThread). Because of so many threads will create while running. can one suggest the good idea to load the data custom listview.

I have seen OnScrollListener but I am not understanding how to implement this for a custom listview.

manager.fetchBitMapThread(data.getImgUrl(),iv);


public class Manager {

ImageView imageView;
final int stub_id=R.drawable.stub;
private final Map<String, Bitmap> bitMap;

public Manager() {
    bitMap = new HashMap<String, Bitmap>();
}

public void fetchBitMapThread(final String urlString, final ImageView imageView) {
    this.imageView = imageView;
    if (bitMap.containsKey(urlString)) {
        imageView.setImageBitmap(bitMap.get(urlString));
    }
    imageView.setImageResource(stub_id);
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            if(!message.equals(null))
            imageView.setImageBitmap((Bitmap) message.obj);
            else
            imageView.setImageResource(stub_id);
        }
    };

    Thread thread = new Thread() {
        @Override
        public void run() {
            // set imageView to a "pending" image
            Bitmap bitM = fetchBitmap(urlString);
            Message message = handler.obtainMessage(1, bitM);
            handler.sendMessage(message);
        }
    };
    thread.start();
}


public Bitmap fetchBitmap(String urlString) {
    if (bitMap.containsKey(urlString)) {
        return bitMap.get(urlString);
    }

    Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
    try {
        InputStream is = fetch(urlString);


        Bitmap drawable = BitmapFactory.decodeStream(is);


        if (drawable != null) {
            bitMap.put(urlString, drawable);
            //Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", " + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", " + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
        } else {
            //wrong.setImageResource(stub_id);
            Log.w(this.getClass().getSimpleName(), "could not get thumbnail");

        }

        return drawable;
    } catch (MalformedURLException e) {
        Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
        //imageView.setImageResource(stub_id);
        return null;
    } catch (IOException e) {

        Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
    //  imageView.setImageResource(stub_id);
        return null;
    }
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(urlString);
    HttpResponse response = httpClient.execute(request);
    return response.getEntity().getContent();
}

}

Upvotes: 1

Views: 3194

Answers (3)

santoshpatmca
santoshpatmca

Reputation: 1752

follow this link to Load images from server in Custom List View. http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_Example/index.php?view=article_discription&aid=112&aaid=134

Download this and try to implement it in your application.

Upvotes: 2

Shachilies
Shachilies

Reputation: 1616

OnScrollListener provides four arguments which are as below:

                   public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount)

As the name suggests , first one is first item which is visible to you on screen ,second one is total no of items which are visible to you and last one tells you total no of itema list has which is in your case is 500+ . So send request to download the images for those itema/rows which are visible to user . BY ding this first less threads will be created second plus point is images will be downloaded much faster .Use placeholder or progreess bar for image view .

Prepare one map for bitmap images and in key as url value . In get view method check bitmap for particular image view position is downloaded or not using hashmap and set progress bar visibility according to that .

For doing above you cant do simply creating a thread (in anonymous inner class) , Do it efficiently by creating a class extending thread and implement one listener which notifies both ui thread and background for image downloaded or not . It will be something like creating a pipeline of thread asynchronus .

I hope above approach could help you in loading 500+ rows without taking time else doing all images download in asynchronous can lead to Bitmap out of memory exception and its very much time taking too.

Upvotes: 1

Krishnakant Dalal
Krishnakant Dalal

Reputation: 3578

Follow this link

http://android-er.blogspot.in/2010/07/load-listview-in-background-asynctask.html

Complete example to load images from server using Async Task and display them in a ListView

Upvotes: 1

Related Questions