Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination in endless recycler view with firebase

I am working on Q/A app . I have successfully loaded questions from firebase . But I am not able to apply pagination from Firebase like database . And how to recognize that we have reached end of recycler view so that next few questions can loaded .

like image 735
Rishabh Maurya Avatar asked Apr 08 '17 03:04

Rishabh Maurya


People also ask

How to implement pagination of Firebase Realtime Database in recyclerview?

Here is Android library to implement Pagination of Firebase Realtime Database in RecyclerView. The Sample app is available in app/ directory that demonstrates feature of this library. Step by step description is given here FirebaseRecyclerPagingation Library binds Firebase Realtime Database Query to a RecyclerView by loading Data in pages.

What is pagination in Android recyclerview?

Pagination is one of the most important factors which helps to reduce the loading time inside our app and increase the performance of our data which is represented in the form of Lists. In this article, we will take a look at adding pagination in our Android RecyclerView .

How to add recyclerview in Android app and display data in Firebase?

How to add RecyclerView in the android app and display the data in Firebase Realtime Database. Log in to Firebase with your Google account if are not already logged in. Click on create the project. Write the name. Click on continue. Click on the toggle button. Click Continue. Firebase will create a project for you and open it for you.

What is pagination and why do you need it?

What is Pagination? Pagination is to load data according to requirement rather than loading complete data at a time. So this helps to reduce the loading time for our data from our API as well as increase the performance of our application. What is the benefit of using Pagination in your lists of data?


2 Answers

To recognize that we have reached end of RecyclerView you can use this class EndlessRecyclerOnScrollListener.java

To load more next question, you should define one more field in Question class like number

public class Question {
    private int number; // it must unique and auto increase when you add new question
    ...
}

Then when you load questions from FireBase you can do like

public class MainActivity extends AppCompatActivity {
    private static final int TOTAL_ITEM_EACH_LOAD = 10;
    private DatabaseReference mDatabase;
    final List<Question> questionList = new ArrayList<>();

    private int currentPage = 0;

    private RecyclerView recyclerView;
    private RecyclerViewAdapter mAdapter; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // init and set layout manager for your RecyclerView
        ...
        mAdapter = new RecyclerViewAdapter(questionList);
        recyclerView.setAdapter(mAdapter);
        recyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
            @Override
            public void onLoadMore(int current_page) { // when we have reached end of RecyclerView this event fired
                loadMoreData();
            }
        });
        loadData(); // load data here for first time launch app
    }

    private void loadData() {
        // example
        // at first load : currentPage = 0 -> we startAt(0 * 10 = 0)
        // at second load (first loadmore) : currentPage = 1 -> we startAt(1 * 10 = 10)
        mDatabase.child("questions")
                .limitToFirst(TOTAL_ITEM_EACH_LOAD)
                .startAt(currentPage*TOTAL_ITEM_EACH_LOAD)
                .orderByChild("number")
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if(!dataSnapshot.hasChildren()){
                            Toast.makeText(MainActivity.this, "No more questions", Toast.LENGTH_SHORT).show();
                            currentPage--;
                        }
                        for (DataSnapshot data : dataSnapshot.getChildren()) {
                            Question question = data.getValue(Question.class);
                            questionList.add(question);
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                   @Override public void onCancelled(DatabaseError databaseError) {}});
    }

    private void loadMoreData(){
        currentPage++;
        loadData();
    }
}

Here is my DEMO project

like image 61
Linh Avatar answered Oct 14 '22 10:10

Linh


To check whether you have reached the bottom of the RecyclerView, you can use the onScrolled listener as below, the if condition here is important and it is defining when a user has reached to the bottom.

mRV.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                mTotalItemCount = mLayoutManager.getItemCount();
                mLastVisibleItemPosition = mLayoutManager.findLastVisibleItemPosition();

                if (!mIsLoading && mTotalItemCount <= (mLastVisibleItemPosition + mPostsPerPage)) {
                    getUsers(mAdapter.getLastItemId());
                    mIsLoading = true;
                }
            }
        });

Secondly, you can use startAt and limitToFirst methods to get questions in batches as shown below:

query = FirebaseDatabase.getInstance().getReference()
                    .child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
                    .orderByKey()
                    .startAt(nodeId)
                    .limitToFirst(mPostsPerPage);

I have created an open source app that shows exactly how it is done. Please have a look: https://blog.shajeelafzal.com/2017/12/13/firebase-realtime-database-pagination-guide-using-recyclerview/

like image 23
Shajeel Afzal Avatar answered Oct 14 '22 10:10

Shajeel Afzal