September 17th, by Tom van Zummeren
|
and I ' m back! Reporting live on the Glorious adventures in the exciting world of Android. This blog post was the second one in the Android series. This time with code samples! yeah!
In my first blog post about Android I talked on setting up a project using Android. This time I want the discuss a more "advanced" Topic:listview performance. A ListView is a view component which allows your to display and scroll through a list of items. It can display simple text on each row, but is the also able to display a more complicated structure. In the latter case, you'll need to make sure your ListView still performs well (read:renders fast and scrolls smoothly). I am going to provide solutions to a few different performance problems when using a ListView
The ListAdapter
If you want to use a in the ListView, you'll have the supply it with a listadapter to allow it to display any content. A Few simple implementations of this adapter is already available in the SDK:
- Arrayadapter<t> (for displaying a array of objects, using toString () to display them)
- Simpleadapter (for displaying a list of Maps)
- Simplecursoradapter (for displaying rows fetched from a database table using a Cursor)
These implementations is perfect for displaying very simple lists. But if your list was just a little more complicated than so, you'll need to write your own custom listadapter implement ation. In the most cases it's useful to subclass Arrayadapter which already takes care of managing a list of objects. Now, only there is a to-tell it what to render each object in the list. Do this by overriding the GetView (int, View, ViewGroup) method of the Arrayadapter class.
A Simple Example
To give your a simple example of a case in which you need to write your own listadapter: Displaying a list of imag Es with some text next to it.
Example of a ListView containing Youtube search results in the form of images and text
The images need to is on-the-fly downloaded from the Internet. Let's create a class which represents items in the list:
public class ImageAndText { private String imageUrl; private String text; Public ImageAndText (String imageUrl, string text) { this.imageurl = IMAGEURL; This.text = text; } Public String Getimageurl () { return imageUrl; } Public String GetText () { return text; }}
Now, let's create an implementation of a ListAdapter that's able to display a list of these imageandtext< /c16>s.
public class Imageandtextlistadapter extends arrayadapter<imageandtext> {public Imageandtextlistadapter ( Activity activity, list<imageandtext> imageandtexts) {super (activity, 0, imageandtexts); } @Override public View getView (int position, view Convertview, ViewGroup parent) {Activity activity = (Acti vity) GetContext (); Layoutinflater inflater = Activity.getlayoutinflater (); Inflate the views from XML View Rowview = inflater.inflate (R.layout.image_and_text_row, NULL); ImageAndText ImageAndText = GetItem (position); Load the image and set it on the ImageView ImageView ImageView = (ImageView) Rowview.findviewbyid (r.id.image); Imageview.setimagedrawable (Loadimagefromurl (Imageandtext.getimageurl ())); Set the text on the TextView TextView TextView = (TextView) Rowview.findviewbyid (R.id.text); Textview.settext (Imageandtext.gettext ()); return rowview; } PUBlic static drawable loadimagefromurl (String url) {InputStream inputstream; try {inputstream = new URL (URL). OpenStream (); } catch (IOException e) {throw new RuntimeException (e); } return Drawable.createfromstream (InputStream, "src"); }}
The views is inflated from an XML file called "Image_and_text_row.xml":
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:orientation=" horizontal " android:layout_width=" fill_parent " android:layout_height = "Wrap_content" > <imageview android:id= "@+id/image" android:layout_width= "Wrap_content " android:layout_height= "Wrap_content" android:src= "@drawable/default_image"/> <textview Android:id = "@+id/text" android:layout_width= "wrap_content" android:layout_height= "Wrap_content"/></ Linearlayout>
This listadapter implementation renders the ImageAndTexts in the ListView like you would expect . The only thing is, and the only works for a very small list which doesn ' t require scrolling to see all items. If the list of ImageAndTexts gets bigger you'll notice that scrolling isn ' t as smooth as it should is (in fact, It ' s far off!).
Improving performance
The biggest bottleneck in the above example are the fact that the images has to been downloaded from the Internet. Because We execute all our code in the same thread as the UI, the UI would get stuck each time a image is being downloaded . If you run the same application using a 3G Internet connection instead of WiFi, the performance would even be worse.
To avoid this we want the image to being loaded in a separate thread to not disturb the UI thread too much. To make the happen, we could use a asynctask which is the designed for cases like this. But in practice, you'll notice that the Asynctask was limited to threads. This number is hardcoded somewhere in the Android SDK so we cannot change this. In this case it's a limitation we cannot live with, because often more than is images at the loaded time.
Asyncimageloader
An alternative are to manually spawn a new Thread for each image. In addition we should use handlers to deliver the downloaded images to the UI thread. We want to does this because only from the UI thread that is allowed to modify the UI (Read:draw a image on the screen). I created a class called Asyncimageloader which takes care of loading images using Threads and Handl ERs like I just described. Also it caches images to avoid a single image to be downloaded multiple times.
public class Asyncimageloader {private hashmap<string, softreference<drawable>> Imagecache; Public Asyncimageloader () {drawablemap = new hashmap<string, softreference<drawable>> (); Public drawable loaddrawable (final String imageUrl, final imagecallback imagecallback) {if (Drawablemap.containsk EY (IMAGEURL)) {softreference<drawable> softreference = Imagecache.get (IMAGEURL); drawable drawable = Softreference.get (); if (drawable! = null) {return drawable; }} final Handler Handler = new Handler () {@Override public void handlemessage (message message) { Imagecallback.imageloaded ((drawable) message.obj, IMAGEURL); } }; New Thread () {@Override public void run () {drawable drawable = Loadimagefromurl (IMAGEURL); Imagecache.put (IMAGEURL, New softreference<drawable> (drawable)); Message MessagE = handler.obtainmessage (0, drawable); Handler.sendmessage (message); }}.start (); return null; } public static drawable loadimagefromurl (String URL) {//...} Public interface Imagecallback {public void imageloaded (drawable imagedrawable, String imageUrl); }}
Notice that I used a softreference for caching images, to allow the garbage collector to clean the images from the cache W Hen needed. How it works:
- Call loaddrawable (IMAGEURL, Imagecallback) providing an anonymous implementation of the Imagecallback Interface
- If the image doesn ' t exist in the cache yet, the image was downloaded in a separate thread and the imagecallback i S called as soon as the download is complete.
- If the image DOES exist in the cache, it's immediately returned and the Imagecallback is never called.
Only one instance of Asyncimageloader should exist in your application, or else the caching won ' t work. If We take the example Imageandtextlistadapter class We can now replace:
ImageView ImageView = (ImageView) Rowview.findviewbyid (r.id.image); Imageview.setimagedrawable (Loadimagefromurl ( Imageandtext.getimageurl ()));
With:
Final ImageView ImageView = (ImageView) Rowview.findviewbyid (r.id.image);D rawable cachedimage = Asyncimageloader.loaddrawable (Imageandtext.getimageurl (), new Imagecallback () {public void imageloaded ( Drawable imagedrawable, String imageUrl) { imageview.setimagedrawable (imagedrawable); }}); Imageview.setimagedrawable (Cachedimage);
Using This approach, the ListView performs a lot better and feels much more smooth because the UI thread is no longer bloc Ked by the loading of images.
Improve the performance even more
If you tried the solution described above you'll notice that the ListView are still not a 100% smooth. You'll still notice some little disruptions that make it a little less smooth than it could be. There is things remaining that can is improved:
- The expensive call to Findviewbyid ()
- Inflating the entire row from XML every time
The solution is obvious:we should cache/reuse these things! Mark Murphy did a very nice job on writing a few blogs entries describing how this can is done. To reuse the which is inflated from XML read this blog entry:
http://www.androidguys.com/2008/07/17/fancy-listviews-part-two/
To cache the views returned by Findviewbyid () Read this blog entry:
http://www.androidguys.com/2008/07/22/fancy-listviews-part-three/
If We apply the strategies described in Mark Murphy's blog entries our imageandtextlistadapter could look lik E The following:
public class Imageandtextlistadapter extends arrayadapter<imageandtext> {private ListView listview; Private Asyncimageloader Asyncimageloader; Public Imageandtextlistadapter (activity activity, List<imageandtext> imageandtexts, ListView listview) {Supe R (activity, 0, imageandtexts); This.listview = ListView; Asyncimageloader = new Asyncimageloader (); } @Override public View getView (int position, view Convertview, ViewGroup parent) {Activity activity = (Acti vity) GetContext (); Inflate the views from XML View Rowview = Convertview; Viewcache Viewcache; if (Rowview = = null) {Layoutinflater inflater = Activity.getlayoutinflater (); Rowview = inflater.inflate (R.layout.image_and_text_row, NULL); Viewcache = new Viewcache (Rowview); Rowview.settag (Viewcache); } else {Viewcache = (Viewcache) rowview.gettag (); } ImageAndText ImageaNdtext = GetItem (position); Load the image and set it on the ImageView String imageUrl = Imageandtext.getimageurl (); ImageView ImageView = Viewcache.getimageview (); Imageview.settag (IMAGEURL); drawable cachedimage = asyncimageloader.loaddrawable (ImageUrl, New Imagecallback () {public void imageloaded (Dr Awable imagedrawable, String imageUrl) {ImageView Imageviewbytag = (ImageView) Listview.findviewwithtag (IM Ageurl); if (Imageviewbytag! = null) {imageviewbytag.setimagedrawable (imagedrawable); } } }); Imageview.setimagedrawable (Cachedimage); Set the text on the TextView TextView TextView = Viewcache.gettextview (); Textview.settext (Imageandtext.gettext ()); return rowview; }}
There is things to notice. The first thing is, the drawable is not directly set to the ImageView anymore after loading. Instead, the right ImageView was looked up through it ' s tag. This is do because we ' re now reusing views and the images might end up on the wrong rows. We need a reference to the ListView -to-lookup imageviews by tag.
The other thing to notice, was that this implementation uses an object called Viewcache. This is, the class for, that object, looks like:
public class Viewcache { private View baseview; Private TextView TextView; Private ImageView ImageView; Public Viewcache (View baseview) { this.baseview = Baseview; } Public TextView Gettextview () { if (TextView = = null) { TextView = (TextView) Baseview.findviewbyid (R.id.text); c9/>} return titleview; } Public ImageView Getimageview () { if (ImageView = = null) { ImageView = (ImageView) Baseview.findviewbyid ( r.id.image); } return imageView;} }
This Viewcache are the same as what Mark Murphy calls a "viewwrapper" and takes care for caching individual views Which normally would has the to being looked up every time using the "expensive call" to Findviewbyid ().
To summarize
I ' ve shown you and improve performance of a ListView in three different ways:
- By loading images in a seperate thread
- By reusing rows in the list
- By caching views within a row
It took me quite some time to figure this stuff out, especially the image loading part. So I thought it's all worth mentioning to avoid you have to waste too much time on it.
Next time I'll discuss other interesting challenges in the world of android!
To be Continued ...
Exploring the world's Android:: Part 2