Search code examples
androidfirebasefirebase-realtime-databasefirebaseui

How do I limit the items FirebaseRecyclerAdapter pulls from the server?


I'm using the tutorial project and can't understand how to limit the number of items pulled.


Solution

  • You can initialize your FirebaseRecyclerAdapter with either a DatabaseReference or with a Query. When you use a DatabaseReference the adapter will show all data at that location. E.g. (from the FirebaseUI docs):

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    DatabaseReference chatRef = ref.child("chat_messages");
    
    mAdapter = new FirebaseListAdapter<Chat>(this, 
                                             Chat.class, 
                                             android.R.layout.two_line_list_item, 
                                             chatRef) {
        @Override
        protected void populateView(View view, Chat chatMessage, int position) {
            ((TextView)view.findViewById(android.R.id.text1)).setText(chatMessage.getName());
            ((TextView)view.findViewById(android.R.id.text2)).setText(chatMessage.getText());
    
        }
    };
    messagesView.setAdapter(mAdapter);
    

    To only show the last 5 chat messages, you'd create a query and pass that into the adapter:

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    DatabaseReference chatRef = ref.child("chat_messages");
    Query recentMessages = chatRef.limitToLast(5);
    
    mAdapter = new FirebaseListAdapter<Chat>(this, 
                                             Chat.class, 
                                             android.R.layout.two_line_list_item, 
                                             recentMessages) {
        @Override
        protected void populateView(View view, Chat chatMessage, int position) {
            ((TextView)view.findViewById(android.R.id.text1)).setText(chatMessage.getName());
            ((TextView)view.findViewById(android.R.id.text2)).setText(chatMessage.getText());
    
        }
    };
    messagesView.setAdapter(mAdapter);
    

    There's a lot more you can do with Firebase Database queries. Read the documentation on sorting and filtering data for more.