Skip to content

Instantly share code, notes, and snippets.

@sab99r
Last active July 6, 2016 17:38
Show Gist options
  • Save sab99r/63ac8377c5ef0852f25e09c19aa0beaa to your computer and use it in GitHub Desktop.
Save sab99r/63ac8377c5ef0852f25e09c19aa0beaa to your computer and use it in GitHub Desktop.
RecyclerView Load More Call from activity
public class MainActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
adapter = new MoviesAdapter(this, movies);
adapter.setLoadMoreListener(new MoviesAdapter.OnLoadMoreListener() {
@Override
public void onLoadMore() {
recyclerView.post(new Runnable() {
@Override
public void run() {
int index = movies.size() - 1;
loadMore(index);// a method which requests remote data
}
});
//Calling loadMore function in Runnable to fix the
// java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error
}
});
recyclerView.setAdapter(adapter);
}
private void loadMore(int index){
//add loading progress view
movies.add(new MovieModel("load"));
adapter.notifyItemInserted(movies.size()-1);
Call<List<MovieModel>> call = api.getMovies(index);
call.enqueue(new Callback<List<MovieModel>>() {
@Override
public void onResponse(Call<List<MovieModel>> call, Response<List<MovieModel>> response) {
if(response.isSuccessful()){
//remove loading view
movies.remove(movies.size()-1);
List<MovieModel> result = response.body();
if(result.size()>0){
//add loaded data
movies.addAll(result);
}else{//result size 0 means there is no more data available at server
adapter.setMoreDataAvailable(false);
//telling adapter to stop calling load more as no more server data available
Toast.makeText(context,"No More Data Available",Toast.LENGTH_LONG).show();
}
adapter.notifyDataChanged();
//should call the custom method adapter.notifyDataChanged here to get the correct loading status
}else{
Log.e(TAG," Load More Response Error "+String.valueOf(response.code()));
}
}
@Override
public void onFailure(Call<List<MovieModel>> call, Throwable t) {
Log.e(TAG," Load More Response Error "+t.getMessage());
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment