Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the data from the Firebase in limit to perform pull to refresh and load more functionality

Yet now i am getting the all data from the FireBase at one time.What i want to do that getting data in LIMITS like 15 records at a time. Like in first time user get the 15 records from the Firebase and when user load more data at the bottom/TOP of the screen than 15 more records should come from Firebase and added to the bottom/TOP of the list.

I have implemented the logic to get the 15 records at a top OR bottom of the database from Firebase like below:-

public class ChatActivity extends AppCompatActivity implements FirebaseAuth.AuthStateListener {

    private FirebaseAuth mAuth;
    private DatabaseReference mChatRef;

    private Query postQuery;
    private String newestPostId;
    private String oldestPostId;
    private int startAt = 0;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        mAuth = FirebaseAuth.getInstance();
        mAuth.addAuthStateListener(this);

        mChatRef = FirebaseDatabase.getInstance().getReference();
        mChatRef = mChatRef.child("chats");

         /////GETTING THE VIEW ID OF SWIPE LAYOUT
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

    /////GETTING FIRST 10 RECORDS FROM THE FIREBASE HERE
        mChatRef.limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot child : dataSnapshot.getChildren()) {
                    oldestPostId = child.getKey();
                    System.out.println("here si the data==>>" + child.getKey());
                }      
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        //////FOR THE PULL TO REFRESH CODE IS HERE
       swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Refresh items  

             System.out.println("Here==>>> "+oldestPostId);

                ///HERE "oldestPostId" IS THE KEY WHICH I GET THE LAST RECORDS FROM THE FIREBASE

                mChatRef.startAt(oldestPostId).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot child : dataSnapshot.getChildren()) {

                    System.out.println("here AFTER data added==>>" + child.getKey());
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

            }
        });
    }

I have searched here on SO for it , but did not get the expected result, below link which i have searched for it

1. First Link
2. Second Link
3. Third Link
4. Forth Link

Please look at my firebase data structure in image.
Data of firebase

I have implemented the logic for the getting 15 OR 10 records at first time and it works..and also implemented the logic for loading more records in limits but not getting proper solution (NOT WORKING) , please help and let me know where am i doing wrong..Thanks :)

EDIT SOLUTION

:- I have implemented the load more or pull to refresh functionality on this link:- Firebase infinite scroll list view Load 10 items on Scrolling

like image 495
Ravindra Kushwaha Avatar asked Feb 28 '17 06:02

Ravindra Kushwaha


People also ask

Can we retrieve data from Firebase?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.

What is the limit of Firebase Storage?

Quota for Hosting storage Storage for your Hosting content is at no cost up to 10 GB. If you are not on the Blaze plan, and you reach the 10 GB limit of no-cost Hosting storage, you won't be able to deploy new content to your sites.

Which function is used for users to listen monitor for changes in the Firebase?

Set the event handler Functions let you handle Realtime Database events at two levels of specificity; you can listen for specifically for only creation, update, or deletion events, or you can listen for any change of any kind to a path.


2 Answers

You are missing orderByKey(). For any filtering queries you must use the ordering functions. Refer to the documentation

In your onRefresh method you need to set the limit:

 public void onRefresh() {
     // Refresh items  
     ///HERE "oldestPostId" IS THE KEY WHICH I GET THE LAST RECORDS FROM THE FIREBASE
                mChatRef.orderByKey().startAt(oldestPostId).limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
.....

So the data you retrieve is the only 10 new records after you got your first 10 records.

Make sure to save the oldest key of the newly retrieved data so that on next refresh new data from this key is only retrieved.

Suggestion: Instead of adding a child value listener to find the last key, you can just use the value listener and get the last data snapshot with the size to get the last record's key.

like image 130
kirtan403 Avatar answered Oct 18 '22 21:10

kirtan403


restructure your database, set a new child id which is incremental like 0,1,2,3... etc

"chats": {
"-KZLKDF": {
  "id": 0,
  "message": "Hi",
  "name":"username"
},

then make a method for query

public void loadFromFirebase(int startValue,int endValue){

mChatRef.orderByChild(id).startAt(startValue).endAt(endValue).addListenerForSingleValueEvent(this);
}

make sure you have implemented addListenerForSingleValueEvent then do adapter related task. Initially call from onCreate method:

loadFromFirebase(0,10);

NB: loading new content in the list you have to be aware with adapter.

like image 3
Milon Avatar answered Oct 18 '22 19:10

Milon