Reputation: 4255
I'm making an app and I'm using grid view to show all of my images, the problem is I have lots of images, about 12,000, and I don't want to load all of them at the start, because lets face it, it will take forever, so I was wondering what is the best way of accessing the server to fetch more items once the gridview has reached the end.
Thanks.
Upvotes: 3
Views: 4668
Reputation: 489
To achieve load more items on scrolled to end of the gridview
gridView.setOnScrollListener(new AbsListView.OnScrollListener(){
@Override
public void onScroll(AbsListView view,
int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
//Algorithm to check if the last item is visible or not
final int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount){
// here you have reached end of list, load more data
fetchMoreItems();
}
}
@Override
public void onScrollStateChanged(AbsListView view,int scrollState) {
//blank, not required in your case
}
});
Upvotes: 2
Reputation: 31015
One way is to start the server request for an image in the adapter getView()
. When the request completes, you set the retrieved bitmap on the ImageView
. There is a very in-depth description of this technique on the Android Developer Blog: Multithreading For Performance | Android Developers Blog. Most servers are fast enough that the lag time to display the image is not objectionable.
However, if you want to load images before the ImageViews
are displayed, here's another way you can do it with an OnScrollListener
, an AsyncTask
, and a list adapter for the `GridView.
Say you have a constant final int THRESHOLD = 50;
and a variable lastItem
that starts at zero.
When user displays your GridView
the AsyncTask
kicks off and retrieves the first 100 images. In the onPostExecute()
, it adds the images to your adapter and calls notifyDataSetChanged()
. It also adds 100 to lastItem
.
So now your adapter has 100 images. The user is scrolling through images and the OnScrollListener
gets called.
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
if (firstVisibleItem >= lastItem - THRESHOLD) {
new FetchImageAsyncTask().execute();
}
}
Your AsyncTask
executes, lastItem
is updated to 200, and your adapter gets 100 more images.
Then the user scrolls some more and it starts all over again.
By using the threshold, the user can scroll another 50 images before the end of the list, and that may be enough time to load the next 100 images.
Upvotes: 0