I'm a 27 year old software developer that mainly focuses on software development. As everyone i have taken a side in the Apple vs Android game. My choice is Android because of oh so many reasons :-) By contributing to the Android developers content online ( in the form of writing Android tutorials ), I hope to convince others to make the same decision and help them make nice content for the Android platform. Mark is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

Android tutorial: Dynamicaly load more items to the ListView ( Never Ending List! )

04.27.2011
| 76256 views |
  • submit to reddit

We pretty much all know the nice technique apps like GMail / Facebook use to dynamically load more items to the ListView then you scroll to the bottom. In this post i want to shed some light on how to make such a list ourselves!

We can approach this from a few sides:

  • The first option is to add a button to the footer of the view. when pressed it will load more content.
  • The second option is to check if the last item is visible and load more content when it is!


I really like the second one, because i think its more user friendly. Android makes checking is a item is in view very easy because they added a function with the following method signature:

public abstract void onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)

As you might have guessed: with these parameters we can easily figure out whats the last item on screen! Before we make this method we will first have to add a footer to the ListView.

More after the breaky break!

Android never ending list

Thats a lot of items!

 

Adding a FooterView to the ListView

A footer View is nothing more than a piece of XML that defines how the footer of your listview will look like. Mine is as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:gravity="center_horizontal"
    android:padding="3dp"
    android:layout_height="fill_parent">
		    <TextView
		           android:id="@id/android:empty"
		           android:layout_width="wrap_content"
		           android:layout_height="fill_parent"
		           android:gravity="center"
		           android:padding="5dp"
		           android:text="Loading more days..."/>
</LinearLayout>

Its just a simple textview with a message for demonstration purposes. But you can put anything in here :-)

Adding the View to the ListView is not hard. The only thing you need to be aware of is that you put it above the line that adds your adapter to the View! We will use this code to add it to our ListView: addFooterView(View)

//add the footer before adding the adapter, else the footer will not load!
View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
this.getListView().addFooterView(footerView);

Now the fun part, checking if we are all the way down and loading the items.

Checking what items are visible in the ListView

As stated above, we have a nice method to do the checking. Here is the code that does all the magic tricks:

//Here is where the magic happens
this.getListView().setOnScrollListener(new OnScrollListener(){
	//useless here, skip!
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {}
	//dumdumdum
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
		int visibleItemCount, int totalItemCount) {
		//what is the bottom iten that is visible
		int lastInScreen = firstVisibleItem + visibleItemCount;
		//is the bottom item visible & not loading more already ? Load more !
		if((lastInScreen == totalItemCount) && !(loadingMore)){
			Thread thread =  new Thread(null, loadMoreListItems);
			thread.start();
		}
	}
});

The actual loading is done in a separate thread (Runnable). This way we don't lock the main interface ( GUI ).

Implementing Runnables to handle the loading

The loading is done by 2 Runnables. The 1st runnable ( loadMoreListItems )is called to get the data and the 2nd runnable ( returnRes ) is called on the main (UI) thread to update the interface. To switch from the 1st to the 2nd we use a method named: runOnUiThread

Here is the code that implements the Runnables, i commented the code as much as i could to make it understandable:

   //Runnable to load the items
   private Runnable loadMoreListItems = new Runnable() {
	@Override
	public void run() {
		//Set flag so we cant load new items 2 at the same time
		loadingMore = true;
		//Reset the array that holds the new items
		myListItems = new ArrayList<String>();
		//Simulate a delay, delete this on a production environment!
		try { Thread.sleep(1000);
		} catch (InterruptedException e) {}
		//Get 15 new listitems
		for (int i = 0; i < itemsPerPage; i++) {
			//Fill the item with some bogus information
        		myListItems.add("Date: " + (d.get(Calendar.MONTH)+ 1) + "/" + d.get(Calendar.DATE) + "/" + d.get(Calendar.YEAR) );
			// +1 day
        		d.add(Calendar.DATE, 1);
		}
		//Done! now continue on the UI thread
       		runOnUiThread(returnRes);
	}
};

And the 2nd Runnable:

//Since we cant update our UI from a thread this Runnable takes care of that!
private Runnable returnRes = new Runnable() {
	@Override
	public void run() {
		//Loop thru the new items and add them to the adapter
		if(myListItems != null && myListItems.size() > 0){
              		for(int i=0;i < myListItems.size();i++)
               		adapter.add(myListItems.get(i));
          		 }
		//Update the Application title
       		setTitle("Neverending List with " + String.valueOf(adapter.getCount()) + " items");
		//Tell to the adapter that changes have been made, this will cause the list to refresh
           		adapter.notifyDataSetChanged();
		//Done loading more.
           		loadingMore = false;
       	}
   };

This is all the magic, for the entire implementation is suggest you download the eclipse project below and mess around with it!

References
Published at DZone with permission of Mark Mooibroek, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)