article from : http://p-xr.com/android-tutorial-dynamicaly-load-more-items-to-the-listview-never-ending-list/

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:

1 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!

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:

01 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
02     android:orientation="horizontal"
03     android:layout_width="fill_parent"
04     android:gravity="center_horizontal"
05     android:padding="3dp"
06     android:layout_height="fill_parent">
07             <TextView
08                    android:id="@id/android:empty"
09                    android:layout_width="wrap_content"
10                    android:layout_height="fill_parent"
11                    android:gravity="center"
12                    android:padding="5dp"
13                    android:text="Loading more days..."/>
14   
15 </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)

1 //add the footer before adding the adapter, else the footer will not load!
2 View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
3 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:

01 //Here is where the magic happens
02 this.getListView().setOnScrollListener(new OnScrollListener(){
03     //useless here, skip!
04     @Override
05     public void onScrollStateChanged(AbsListView view, int scrollState) {}
06     //dumdumdum
07     @Override
08     public void onScroll(AbsListView view, int firstVisibleItem,
09         int visibleItemCount, int totalItemCount) {
10         //what is the bottom iten that is visible
11         int lastInScreen = firstVisibleItem + visibleItemCount;             
12         //is the bottom item visible & not loading more already ? Load more !
13         if((lastInScreen == totalItemCount) && !(loadingMore)){
14             Thread thread =  new Thread(null, loadMoreListItems);
15             thread.start();
16         }
17     }
18 });

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:

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

And the 2nd Runnable:

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

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

+ Recent posts