Android Sina Weibo client (vii) images in--listview asynchronous loading, caching

Source: Internet
Author: User

Source: Miroslav | http://fangjie.sinaapp.com/?p=193 Reprint please indicate the source

Final Effect Demo: http://fangjie.sinaapp.com/?page_id=54
The project code has been put into Github:https://github.com/jayfang1993/sinaweibo

I. Picture of a ListView asynchronous loading
We all know that there are user avatars for every Weibo item, and each tweet may also have pictures. If loading the list at the same time load the picture, so there are several shortcomings, the first very troublesome, the interface stuck, the user experience is not good, the second Android in the main thread can not have network operation, it is very troublesome to implement itself. That's why we implemented a picture asynchronous load class. Inherit from Asynctask<string, Void, Bitmap>, overloaded with methods. Doinbackground is the real asynchronous operation, do some time-consuming tasks, here is to download the image on the server, OnPostExecute is called at the end of the Doinbackground, and passed in Doinbackground return value.

     PublicAsyncimageloader (ImageView image, Lrucache<string, bitmap> LruCache,intWidthintheight) {          Super();  This. Image =image;  This. LruCache =LruCache;  This. width=width;  This. height=width; } @OverrideprotectedBitmap doinbackground (String ... params) {Bitmap Bitmap=NULL; Bitmap= Getuserinfo.getbitmap (params[0]); if(width!=0&height!=0) Bitmap=getuserinfo.scaleimg (bitmap, width, height); Addbitmaptomemorycache (params[0], bitmap); returnbitmap; } @Overrideprotected voidOnPostExecute (Bitmap Bitmap) {image.setimagebitmap (BITMAP); }

Then encapsulate an interface LoadBitmap in Weiboadapter and load the picture.

Two. ListView Picture Cache

The ListView often slides up and down, and these picture loading tasks are called repeatedly, which can be wasteful. Can be cached for the picture, when a picture has been loaded and needs to be displayed again only need to be taken out of memory to show it, do not need to load. The cache actually has two kinds of caches, one is the memory cache, the other is the SD card cache, that is, the download image to the SD card. Here we only talk about memory caches.

Combined with the above image asynchronous loading, the whole picture shows the process is: when the need to display the picture, first go to the memory to see if there is a cache of this image, and some words directly displayed, no words, go to asynchronous loading, and then save to the memory cache, and then display.

The complete Asyncimageloader.java code

 PackageCom.fangjie.weibo.util;ImportAndroid.graphics.Bitmap;ImportAndroid.os.AsyncTask;ImportAndroid.support.v4.util.LruCache;ImportAndroid.widget.ImageView; Public classAsyncimageloaderextendsAsynctask<string, Void, bitmap> {    PrivateImageView image; PrivateLrucache<string, bitmap>LruCache; Private intwidth; Private intheight; /*** Construct method, need to pass ImageView control and LRUCache object to come in *@paramImage Loads the image to this {@code}imageview *@paramLruCache objects that cache pictures*/       PublicAsyncimageloader (ImageView image, Lrucache<string, bitmap> LruCache,intWidthintheight) {          Super();  This. Image =image;  This. LruCache =LruCache;  This. width=width;  This. height=width; } @OverrideprotectedBitmap doinbackground (String ... params) {Bitmap Bitmap=NULL; Bitmap= Getuserinfo.getbitmap (params[0]); if(width!=0&height!=0) Bitmap=getuserinfo.scaleimg (bitmap, width, height); Addbitmaptomemorycache (params[0], bitmap); returnbitmap; } @Overrideprotected voidOnPostExecute (Bitmap Bitmap) {image.setimagebitmap (BITMAP); }          //call LRUCache's Put method to add a picture to the memory cache, to give the picture a key to facilitate the next time to remove from the cache    Private voidAddbitmaptomemorycache (String key, Bitmap Bitmap) {if(Getbitmapfrommemorycache (key) = =NULL) {lrucache.put (key, bitmap); }      }          //call LRUCache's Get method to go from the memory cache to the picture     PublicBitmap Getbitmapfrommemorycache (String key) {returnLrucache.get (key); }  }

The calling interface in Weiboadapter, LoadBitmap

    Private Final intMaxMemory = (int) Runtime.getruntime (). MaxMemory ();//gets the maximum memory allocated by the current application    Private Final intCacheSize = MAXMEMORY/5;//It's a 5-point one for the picture cache.    Privatelrucache<string, bitmap> Mlrucache =NewLrucache<string, bitmap>(cacheSize) {protected intSizeOf (String key, Bitmap Bitmap) {//The replication sizeof () method//replaced by GetByteCount () in API            returnBitmap.getrowbytes () * bitmap.getheight ()/1024;//Here's how many kilobytes to count.        }      }; /**     *      * @paramurlstr The URL of the image to be loaded in string form, you can use this URL as a key to the cached image *@paramImage ImageView Control*/    Private voidLoadBitmap (String urlstr, ImageView image,intWidthintheight)        {System.out.println (URLSTR); Asyncimageloader Asyncloader=NewAsyncimageloader (image, Mlrucache,width,height);//What an asynchronous picture loads an objectBitmap Bitmap = Asyncloader.getbitmapfrommemorycache (URLSTR);//first get the picture from the memory cache        if(Bitmap! =NULL) {image.setimagebitmap (bitmap);//If this image is present in the cache, it is set directly to ImageView}Else{image.setimageresource (r.drawable.user_head);//otherwise set the default picture firstAsyncloader.execute (URLSTR);//then execute the asynchronous task Asycntask to load the picture online        }    }

At this point, the Weibo page of the microblog list is loaded and completed. There are a lot of small points are not mentioned, but there are source code, I believe we can read. The entire project document:

The code is put in: Http://git.oschina.net/fangjie/Sina-Weibo Effect show: http://fangjie.sinaapp.com/?page_id=54

Note : Due to the application of Sina Weibo development platform application is not approved, so not all the Weibo account can be authorized success, need to test, you can find me, You can also change the source code (COM.FANGJIE.WEIBO.UTIL.AUTHUTIL) to the appkey,appsecret you are applying for.

Weibo client projects have time to write down!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.