Search code examples
androidfirebasefirebase-realtime-databaseandroid-recyclerviewdata-retrieval

How to get Firebase database saved data according to date?


I stored my data on Firebase according to auto-created ID. But now I need to get only today's added data from the database and populate a recycle view with it.enter image description here


Solution

  • I assume branch users storing users information. You can add child event listener to branch users to get users as follows in your activity or fragment.

    private ArrayList<User> userArray = new ArrayList<>();
    private DatabaseReference mDatabase;
    mDatabase = FirebaseDatabase.getInstance().getReference().getChild("users");
    
    ChildEventListener childEventListener = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
            User user = dataSnapshot.getValue(User.class);
            if(user.getDate().equals(today)){
               userArray .add(user);
            }
        }
    
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
           //do somethings
        }
    
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
           //...
        }
    
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
           //...
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
           //...
        }
    };
    

    Inside activity/fragment method, add the listener to your reference:

    ref.addChildEventListener(childEventListener);
    

    The array will be filled out with data from branch users. For more information how to work with list in firebase: https://firebase.google.com/docs/database/android/lists-of-data