Hello Am facing a particular problem in which I need to download images and display them onto a ListView corresponding to their particular TextView\'s
Here's how I load and cache images in a ListView that creates a contact list for the user. So imagine profile picture on the left, some text views on the right (which sounds close to the problem you're dealing with. Ignore the ugly debug tags and probably poor formatting (sorry). I guess this is kind of like LazyList but here's a detailed explanation in case anyone was confused.
Step 1: Set Up Your Cache
private LruCache memoryCache;
private HashMap idPairs = new HashMap();
In my approach I use an LruCache and a HashMap to track which user's images I've downloaded. You'll see how its implemented later but the idea is to avoid downloading stuff from the server unless you have to. Then in your onCreate() or some related method, initialize your cache.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
memoryCache = new LruCache(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap){
return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024; //don't use getByteCount for API < 12
}
};
My next step is to add the default "empty image" bitmap to the cache in case I reach an entry that does not have a picture associated with it. That way I only have to process and add this bitmap once
Bitmap defaultPicture = BitmapFactory.decodeResource(getResources(), R.drawable.default_user_picture);
addBitmapToMemoryCache("default", defaultPicture);
Then its time to get the data you need for the list!
Step 2: Get The Data
private class GetPeopleData extends AsyncTask {
@Override
protected Void doInBackground(JSONArray...lists) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost();
ResponseHandler responseHandler = new BasicResponseHandler();
if(DEBUG) Log.d("GET PEOPLE DATA TASK", lists[0].length() + " users");
getUsers(lists[0], httpClient, httpPost, responseHandler);
return null;
}
@Override
protected void onPostExecute(Void result){
updateUserListView();
}
}
Here's a borring AsyncTask that takes a JSONArray of user data as an argument. I left out that part because it's pretty much just a basic HTTP download that doesn't need explanation. The getUsers method is where I start to put together what will be added to my ListView. What I do next is process the JSON downloaded from the server to create user objects that will be added it to a list of users that will be displayed.
private void getUsers(JSONArray userArray, HttpClient httpClient, HttpPost httpPost, ResponseHandler responseHandler){
if(DEBUG) Log.d("USERS ARRAY", userArray.length() + " users");
try{
users = new ArrayList();
if(DEBUG) Log.d("User Array -START", "" + users.size());
//Go through userArray and get information needed for list
for(int i = 0; i < userArray.length(); i++){
User u = new User();
if(DEBUG) Log.d("User Array - ADD USER", "" + users.size());
String profileId = userArray.getJSONObject(i).getString("profileid");
u.setId(userArray.getJSONObject(i).getString("id"));
u.setDisplayName(userArray.getJSONObject(i).getString("displayname"));
u.setStatus(userArray.getJSONObject(i).getString("status"));
//check HashMap for sender/profileid pair
if(idPairs.containsKey(profileId)){
if(DEBUG) Log.d("idPairs", "User in HashMap");
profileId = idPairs.get(profileId);
} else {
if(DEBUG) Log.d("idPairs", "User not in HashMap. Add profileId");
idPairs.put("profileId", profileId);
}
u.setProfilePicture(getProfilePictureFromCache(profileId, httpClient, httpPost, responseHandler)); //check cache for image
users.add(u);
if(DEBUG) Log.d("User info", u.toString());
}
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
}
I associate the picture with the user object that will eventually be displayed. I figure this isn't a total waste of time since the image is pulled from the bitmap cache
private Bitmap getProfilePictureFromCache(String profileId, HttpClient httpClient, HttpPost httpPost, ResponseHandler responseHandler){
Bitmap defaultPicture = getBitmapFromMemCache("default");
Bitmap profilePicture = getBitmapFromMemCache(profileId);
if(profilePicture != null){
return profilePicture;
} else {
String pictureString = getProfilePic(profileId, httpClient, httpPost, responseHandler);
if(!pictureString.isEmpty()){
byte[] decodedString = Base64.decode(pictureString, Base64.DEFAULT);
profilePicture = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
addBitmapToMemoryCache(profileId, profilePicture);
if(DEBUG) Log.d("MEMCACHE", "Download and store picture for " + profileId);
return profilePicture;
} else if (defaultPicture != null && pictureString.equals(null)) {
if(DEBUG) Log.d("MEMCACHE", "Load default picture");
return defaultPicture;
}
}
return defaultPicture;
}
If a picture exists in the cache it is returned, if not it is downloaded. For me, displaying users, each picture is cached according to userid so even if someone were to appear more than once in the list, there would only be one picture stored in the cache for that user.
ImageView profile_picture = (ImageView) v.findViewById(R.id.profile_picture);
if(profile_picture != null){
profile_picture.setImageBitmap(u.getProfilePicture());
}
The only thing left to do is find the ImageView in your adapter and set that view to the picture you associated with the object in your list.