ResponseListener - Interface for the AsyncTask to return the fresh data back to the Activity.

LazyLoader - The Main Component !! Basically an OnScrollListener . When the List is scrolled, this listener does some basic calculations to check if the user is nearing the end of the List. If yes, then a loadMore() method is called.

So here's the code. :

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ArrayAdapter<String> adapter ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create the ListView
ListView listView = new ListView(this);
// add a ProgressBar as ListView's footer to indicate data load
listView.addFooterView(new ProgressBar(this));
// create an adapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
// plug the adapter to the ListView
listView.setAdapter(adapter);
// set the ListView as the activity's content
setContentView(listView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// CRUCIAL PART !! Add the LazyLoader as the onScrollListener for the ListView.
listView.setOnScrollListener(new LazyLoader() {
// This method is called when the user is nearing the end of the ListView
// and the ListView is ready to add more items.
@Override
public void loadMore(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// The ListView needs more data. So Fetch !!
loadItems();
}
});
}
// Called by the LazyLoader when the ListView is ready for fresh data.
private void loadItems() {
// Index is required to fetch the next set of items
int startIndex = adapter.getCount();
// Fetch more items Asynchronously.
new FetchItemsTask(startIndex, responseListener).execute();
}
// The FetchItemsTask delivers the new data to this listener in the main thread.
private ResponseListener responseListener = new ResponseListener() {
@Override
public void onResponse(List<String> newItems) {
// append the fresh data to the ListView.
adapter.addAll(newItems);
}
};
}

In the onCreate() method, we create a ListView, set an adapter to it AND set an OnScrollListener. The scrollListener's loadMore() method is called when the ListView is nearing its end and needs more data.
In loadMore(), an AsyncTask fetches more data and appends it to the ListView.

The onScroll() method of the onScrollListener is called when the user scrolls the ListView.
In this method, we do calculations to check if the List is nearing its end. If yes, the loadMore() method is called. We have implemented the loadMore() method in the MainActivity, which will append the ListView with more data.