Android ListViews with Dynamic Data

Ed’s Note: This is an article based on a tecnique presented in the book Android UI In Action by Neil Davies. For Source Code, Sample Chapters, the Author Forum and other resources, go to http://www.manning.com/davies/

In a lot of cases, ListViews need to display sets of dynamic data that are loaded at runtime. Have a think about some of the apps you might use, news reading apps, social media, TV guides, and so on. All of these applications will load data at runtime from a server. Often, applications will display this data in a List. To do this, they’ll commonly use a REST Web Service, where requests are made using HTTP messages and responses are returned as serialized objects, commonly in an XML or JSON format. Let’s take a look at an example so that we can explore some of these concepts.

A sample dynamic ListView using Picasa

In this example, we are going to build a ListView that loads data from the Picasa web API and displays it in list. We’ll do this in a number of steps.

First, we’ll create a ListView with an empty data set.

Secondly, the data for the feed will be retrieved.

Finally, we’ll lazily load the images for each item in the List as they are needed

To do this, we’ll make use of Async tasks to make the request to the Web API, so that we don’t block the main UI thread. We’ll request that the data is returned as a JSON string and we’ll decode the JSON using the very useful and easy to use GSON library. Before we look at how to code this, let’s take a look at the steps involved in creating this type of ListView.

Initializing the ListView

Before we can begin loading data for the ListView, we first need to set it up in an initial empty state. To do this, we’ll use a ListActivity that will load the layout for the list. The layout will contain a list view and an empty view. The ListActivity will then create an Adapter that is empty and assign it to the ListView. Since the Adapter is empty and does not contain any data, the ListView will display the empty view, in this case, a TextView loaded from the layout. Figure 1 outlines the initialization process.

Figure 1: Initializing an empty Listview

Load data with an Async Task

Once we have initialized the ListView, we then need to retrieve the data to populate it. To do this, the ListActivty starts an Asynchronous task to load data from the Picasa service. Here, we make a request to the Picasa API via a HTTP get. Once we get the data back from Picasa, we update the ListAdapter so that it now has a populated ArrayList of this data, we then call notifyDataSetChanged so that the ListView can be updated and drawn with the populated data. Figure 2 gives an overview of the process for retrieving the data from the Picasa service.

Figure 2 Loading Picasa data with Async Task

Loading the image bitmaps

The data that we’ve just loaded and populated into the Arraylist contains information such as title, description, and URL paths to images. It does not contain the actual bitmap data for the images themselves. Therefore, the last thing that needs to be done is to load the image data for the images in each list item. As already mentioned, the image data is loaded lazily, and, until the list item with an image is displayed, the data for the image will not be retrieved. So how is the image data loaded only when we need it?

Each Adapter has a getView method that is called when a List needs to display a List item. So, as you scroll through a List, getView will be called each time a new view is displayed. It is here in getView that we implement the lazy loading of the image data. Remember that we have already populated an ArrayList of the feed data. So, each time getView is called, we simply assign the text strings for the title and description to the appropriate views in the list item.

For each image, we need to do a little extra work. The feed data only gives us a URL for the image. We use this URL to make another Asynchronous call to the Picasa server from within the Adapters getView method. The class that we will use to make this Asynchronous call is ImageDownloader. Once the data is loaded, we update the ImageView for the respective list item. To add a little UI magic, we also use a crossfade effect between the default image and the newly loaded image.

Figure 3 describes this process.

Figure 3 Loading the Image for each list item on the ListViews call to getView

Essentially, there are three steps to our example: first, we initialize an empty ListView; second, we load the feed data; and, to finish, we then lazily load the image data as each item in the list is displayed.

Implementing a dynamic ListView

With the overview of how we are going to implement our ListView fresh in our minds, let’s have a look at the implementation details of how we really go about dynamically loading data into a ListView. The first thing we will have to do is create the XML for our Listview layout, as shown in listing 1.

Here, we have a LinearLayout that contains two items, a Listview (#1) and a TextView (#2). The ListView is there to display the list of data that we will load, but what about the TextView? This view is displayed only when we don’t have data, it could be any type of view we like but for now we are just going to use a TextView that displays the String “Loading feed data.” The important point to notice here is that both of ListView and the TextView have specific ids that must be correct. The ListView must have an id of @android:id/list and the TextView must have and id of @android:id/empty. Otherwise, the ListActivty will not know which views to use for the List and its empty alternative view when there is no data to display.

So that’s the main layout done, let’s not forget that we also need a layout for each list item. For this, we’ll just reuse the list item layout that we defined in the previous example here it is again in listing 2.

The Adapter in this Activity does a little more than the Adapter in our previous example, but, for now, let’s look at the LoadFeedData class that we instantiate and call execute on #3 in the onCreate method of our ListActivity. The LoadFeedData class hopefully has a fairly self-explanatory name. Its job is to load the feed data; in this example, it will retrieve that data from the Picasa web API. Let’s take a look at this class.

Taking a closer look at LoadFeedData, we can see that it is an Async class. The Android Async class allows us to execute code on a different thread to the main Android UI thread. By calling the execute method on an Async task, we instruct it to execute any code that is in its doInBackground method on a separate background thread. A full explanation of the Async task is beyond the scope of this example, but more information on these very useful classes can be found on the Android developers’ web site at http://developer.android.com/reference/android/os/AsyncTask.html.

Stepping through the code in this class, we can see that the first thing we do is set up a URL (#2). This URL makes up a query to the Picasa API. The Arguments state that we want to retrieve a maximum of 20 images that are of thumbnail size and relate to landscapes and sunsets. Also we state that we want the data to be returned in a JSON format. For the purpose of keeping things simple this URL is hard coded, but it is of course possible to build URLs that can make queries of many varying types at runtime. The constructor of LoadFeedData class take a reference to the Adapter for the ListView (#3), so that we can notify it when we have retrieved the feed data from the Picasa API.

All the main work of this class happens in the doInBackground method. Here we use the private method retrieveStream (#4) to return an InputStream. The InputStream contains a serialized data object in a JSON format. To transform the JSON string into objects that we can work with, we use a class from the GSON library and call the method fromJson (#5) while passing the InputStream a class that we want the JSON data mapped into.

To parse the JSON data we use GSON, which is library. The GSON library is a powerful way to deserialize data from existing JSON strings and can also be used to serialize objects to JSON strings. More information on GSON can be found here: https://sites.google.com/site/gson/Home.

All we have to do to get the data from the JSON string is to supply classes that have attributes that map directly to the attributes in the JSON string. The GSON class will take care of the details for us.

Once we have retrieved the data from the Picasa web API we then pass this data as an array of Entry objects to the Adapter via the UpdateEntries method (#6). The Adapter will then have a populated ArrayList of image data and also notify the ListView that this is the case so that the ListView can display this data. Let’s take a closer look at the Adapter that we use in this example.

Listing 5 ImageListAdapter used to populate ListView with data and images

Here we can see that our Adapter is called ImageListAdapter. This adapter is a fairly typical Adapter with all the methods that we would expect. Of course, getView (#5) is where most of the work is done.

When is getView called?
Remember that the getView method of an Adapter is called every time a List needs to display a List Item. So, when a List item is initially displayed, this method will be called a number of times so that each list item currently displayed can be populated with the data contained in the Adapter. As we scroll the list and new list items come into view, getView will again be called as each list item is displayed.

Our getView method is a fairly standard example. The whole aim of this method is to populate each list item with data, in this case, the ArrayList of Entry classes that we retrieved from the Picasa web API.

The one thing that is done differently here is how we populate the Image for the list item. Here we get the URL (#8) for the image for this list item, and pass both the URL and a reference to the ImageView for the list item to the ImageDownloader class by calling its download method (#9). This method will asynchronously load the data for the image and update the Image once it’s done. This is done in a lazy fashion because getView will only be called when a list items needs to be displayed, hence the image will only be retrieved only when a list item is shown and the image is needed.

The main aim of the ImageDownloader is to asynchronously load images, but it also caches images in memory. Our ImageDownloader class has a few tweaks made to it so we can add the possibility of caching images to disk and also so we can add a crossfade transition between the initial image we show in the list and the final downloaded image.

To add the crossfade functionality we use another class called CrossFadeDrawable. This class is again based on previously written code. Romain Guy, a Google engineer, originally created this class in an open source project called shelves, which has some nice code techniques in it and is worth taking time to look at. We have made a tweak to this class so it does exactly what we need. Here our tweak is to add a matrix transformation that scales our downloaded image to the size of our start image, since the original class assumed that the default start image was the same size as the downloaded end image.

If you'd like to know more about the ImageDownloader and CrossFadeDrawable classes the full source code for these classes and the other classes in this example are available on this book’s companion website.

Summary

Great, that’s it! We covered all the different techniques we need to load dynamic data and images and display them in a list, and to put some icing on the cake we’ve also added a few nice additions such as an empty loading screen and a transitional crossfade between each list items default image and its final downloaded image.

by dancelee331 (0 replies)

by dancelee331 (0 replies)

Published 4 years ago, running time 0h0m

Roundup ‘12 - Mobile Business ModelsFully formatted shownotes can always be found at http://javaposse.comRecorded at the Java Posse Roundup 2012 in Crested Butte, COThanks to Brad Kizzort for production help. *Multi-platform app development *PhoneGap www.phonegap.com