Exploring the world of Android

来源:互联网 发布:怎么能在淘宝上买东西 编辑:程序博客网 时间:2024/05/18 01:35

Exploring the world of Android :: Part 2

September 17th, 2009 by Tom van Zummeren
| Reply

And I'm back! Reporting live on the glorious adventures in the exciting world of Android. This blog post is the second one in the Android series. This time with code samples! Yeah!

In my first blog post about Android I talked about setting up a project using Android. This time I want to discuss a more "advanced" topic:ListView performance. A ListView is a view component which allows you to display and scroll through a list of items. It can display simple text in each row, but is also able to display a more complicated structure. In the latter case you will 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 aListView

The ListAdapter

If you want to use a ListView, you will have to supply it with a ListAdapter to allow it to display any content. A few simple implementations of that adapter are already available in the SDK:

  • ArrayAdapter<T> (for displaying an array of objects, usingtoString() to display them)
  • SimpleAdapter (for displaying a list ofMaps)
  • SimpleCursorAdapter (for displaying rows fetched from a database table using aCursor)

These implementations are perfect for displaying very simple lists. But if your list is just a little more complicated than that, you will need to write your own customListAdapter implementation. In most cases it's useful to subclass ArrayAdapter which already takes care of managing a list of objects. Now you only have to tell it how to render each object in the list. Do this by overriding thegetView(int, View, ViewGroup) method of the ArrayAdapter class.

A simple example

To give you a simple example of a case in which you need to write your own ListAdapter: displaying a list of images with some text next to it.

images with text in a ListView
Example of a ListView containing Youtube search results in the form of images and text

The images need to be on-the-fly downloaded from the internet. Let's create a class which represents items in the list:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ImageAndText {
    privateString imageUrl;
    privateString text;
 
    publicImageAndText(String imageUrl, String text) {
        this.imageUrl = imageUrl;
        this.text = text;
    }
    publicString getImageUrl() {
        returnimageUrl;
    }
    publicString getText() {
        returntext;
    }
}

Now, let's create an implementation of a ListAdapter that is able to display a list of theseImageAndTexts.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class ImageAndTextListAdapter extendsArrayAdapter<ImageAndText> {
 
    publicImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts) {
        super(activity,0, imageAndTexts);
    }
 
    @Override
    publicView getView(intposition, View convertView, ViewGroup parent) {
        Activity activity = (Activity) 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());
         
        returnrowView;
    }
 
    publicstatic Drawable loadImageFromUrl(String url) {
        InputStream inputStream;
        try{
            inputStream =new URL(url).openStream();
        }catch (IOException e) {
            thrownew RuntimeException(e);
        }
        returnDrawable.createFromStream(inputStream, "src");
    }
}

The views are inflated from an XML file called "image_and_text_row.xml":

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content">
 
        <ImageViewandroid:id="@+id/image"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:src="@drawable/default_image"/>
 
        <TextViewandroid:id="@+id/text"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"/>
 
</LinearLayout>

This ListAdapter implementation renders the ImageAndTexts in theListView like you would expect. The only thing is that this only works for a very small list which doesn't require scrolling to see all items. If the list ofImageAndTexts gets bigger you will notice that scrolling isn't as smooth as it should be (in fact, it's far off!).

Improving performance

The biggest bottleneck in the above example is the fact that the images have to be downloaded from the internet. Because we execute all our code in the same thread as the UI, the UI will get stuck each time an image is being downloaded. If you run the same application using a 3G internet connection instead of WiFi, the performance will even be worse.

To avoid this we want the image to be loaded in a separate thread to not disturb the UI thread too much. To make this happen, we could use anAsyncTask which is designed for cases like this. But in practice, you will notice that theAsyncTask is limited to 10 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 10 images are loaded at the same time.

AsyncImageLoader

An alternative is 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 do this because only from the UI thread you are allowed to modify the UI (read: draw an image on the screen). I created a class calledAsyncImageLoader which takes care of loading images using Threads andHandlers like I just described. Also it caches images to avoid a single image to be downloaded multiple times.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class AsyncImageLoader {
    privateHashMap<String, SoftReference<Drawable>> imageCache;
 
    publicAsyncImageLoader() {
        drawableMap =new HashMap<String, SoftReference<Drawable>>();
    }
 
    publicDrawable loadDrawable(finalString imageUrl, finalImageCallback imageCallback) {
        if(drawableMap.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            Drawable drawable = softReference.get();
            if(drawable != null) {
                returndrawable;
            }
        }
        finalHandler handler = newHandler() {
            @Override
            publicvoid handleMessage(Message message) {
                imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
            }
        };
        newThread() {
            @Override
            publicvoid run() {
                Drawable drawable = loadImageFromUrl(imageUrl);
                imageCache.put(imageUrl,new SoftReference<Drawable>(drawable));
                Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
            }
        }.start();
        returnnull;
    }
 
    publicstatic Drawable loadImageFromUrl(String url) {
        // ...
    }
 
    publicinterface ImageCallback {
        publicvoid 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 when needed. How it works:

  • Call loadDrawable(imageUrl, imageCallback) providing an anonymous implementation of theImageCallback interface
  • If the image doesn't exist in the cache yet, the image is downloaded in a separate thread and theImageCallback is called as soon as the download is complete.
  • If the image DOES exist in the cache, it is 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 exampleImageAndTextListAdapter class we can now replace:

?
1
2
ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
imageView.setImageDrawable(loadImageFromUrl(imageAndText.getImageUrl()));

with:

?
1
2
3
4
5
6
7
final ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
Drawable cachedImage = asyncImageLoader.loadDrawable(imageAndText.getImageUrl(),new ImageCallback() {
    publicvoid 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 blocked by the loading of images.

Improve the performance even more

If you tried the solution described above you will notice that the ListView is still not a 100% smooth. You will still notice some little disruptions that make it a little less smooth than it could be. There are two things remaining that can be 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 blog entries describing how this can be done. To reuse the views which are 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 like the following:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class ImageAndTextListAdapter extendsArrayAdapter<ImageAndText> {
 
    privateListView listView;
    privateAsyncImageLoader asyncImageLoader;
 
    publicImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts, ListView listView) {
        super(activity,0, imageAndTexts);
        this.listView = listView;
        asyncImageLoader =new AsyncImageLoader();
    }
 
    @Override
    publicView getView(intposition, View convertView, ViewGroup parent) {
        Activity activity = (Activity) 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() {
            publicvoid imageLoaded(Drawable imageDrawable, String imageUrl) {
                ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
                if(imageViewByTag != null) {
                    imageViewByTag.setImageDrawable(imageDrawable);
                }
            }
        });
        imageView.setImageDrawable(cachedImage);
 
        // Set the text on the TextView
        TextView textView = viewCache.getTextView();
        textView.setText(imageAndText.getText());
         
        returnrowView;
    }
}

There are two things to notice. The first thing is that the drawable is not directly set to theImageView anymore after loading. Instead, the right ImageView is looked up through it's tag. This is done because we're now reusing views and the images might end up on the wrong rows. We need a reference to theListView to lookup ImageViews by tag.

The other thing to notice, is that this implementation uses an object called ViewCache. This is what the class for that object looks like:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class ViewCache {
 
    privateView baseView;
    privateTextView textView;
    privateImageView imageView;
 
    publicViewCache(View baseView) {
        this.baseView = baseView;
    }
 
    publicTextView getTextView() {
        if(textView == null) {
            textView = (TextView) baseView.findViewById(R.id.text);
        }
        returntitleView;
    }
 
    publicImageView getImageView() {
        if(imageView == null) {
            imageView = (ImageView) baseView.findViewById(R.id.image);
        }
        returnimageView;
    }
}

This ViewCache is the same as what Mark Murphy calls a "ViewWrapper" and takes care of caching individual views which normally would have to be looked up every time using the expensive call tofindViewById().

To summarize

I've shown you how to 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 is all worth mentioning to avoid you having to waste too much time on it.

Next time I will discuss other interesting challenges in the world of Android!

TO BE CONTINUED ...


原创粉丝点击