Firebase infinite scroll list view Load 10 items on Scrolling [duplicate]
Asked Answered
B

1

5

I'm looking for a way to implement a simple list view scrolling in my Firebase app, but I am not getting any way out how to implement this. I have already tried 2-3 tutorials and documentation available on the Internet, but didn't the required result.

In my app I want scrolling like at starting first 10 list items load then each time on scrolling next 10 or 20 items will load until the last item appears at the bottom of the list.

So I tried retrieving first 10 items the following way :

ArrayList<Event> event=new ArrayList<>();

Dbref = FirebaseDatabase.getInstance().getReference("/event");
Dbref.startAt(1).limitToLast(10).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Log.e("Events.java ", "range query started! : " + dataSnapshot.getChildrenCount());
                String event_id = snapshot.child("details").child("event_id").getValue().toString();
                e=new Event(event_id); //Event is a model class for list items
                event.add(e);
                Log.e("ShowEventInfo : ", "" + event_id);
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    adapter=new Event_CustomAdapter(getActivity(),event); 
    ls.setAdapter(adapter); //here ls is instance of ListView

I referred this Youtube Video to implement this feature: (https://www.youtube.com/watch?annotation_id=annotation_3916642001&feature=iv&src_vid=YMJSBHAZsso&v=XwIKb_f0Y_w)

In the above code, as you can see I am generating Log to check if data is fetched from the firebase, but I got no output Android monitor.

I have no idea how can I implement Firebase Scrolling in my list view. I think this is a common problem for those who implement infinite-scroll in recycler view/ list view.

Could you please help me implementing this feature. Thanks.

Brilliancy answered 27/6, 2017 at 10:27 Comment(7)
No its not, the link you have mentioned is explaining update data on pull to refresh but i want to update my list view on scrolling so now can you please remove the duplicate tag as i very much need answer of this problem. @RavindraKushwahaBrilliancy
Please check my question and their answer..U will infidelity rid off from this problem..Their is no difference in my question and urs...On scoll of list/recyclview u need to call that function which bring urs more data..Plusch
Actually i have already gone through your link before posted this question here but i did not find it useful but if u want to help Can you please tell me how can i use your method in listview onScrollListener as thats what i wantBrilliancy
Definitely i will give the answer of urs question after some time.But my main concern is that u are not trying to understand from that code..Same solution is applicable for u..So plz try it..And than if u will not get any thing..Than i will ready to help u...I am here to help u man..Not for marking any question as duplicate :PPlusch
Hey there i get the list view in the same manner 10 items on scrolling but it is repeating the last item (10th item) each time. can you help me how can i resolve this?Brilliancy
Yes sure..Before EOD, will post the answerPlusch
Please check below solution and let me know in case of concernPlusch
P
13

Here we will use the DatabaseReference;s methods which are limitToFirst(int) OR limitToLast(int) to get the first or last records from FireBase.

In below example i am using the limitToFirst(int) to get only top specified records from Firebase. Here i am playing with oldestPostId which is the last or 10th key of our record.

  private String oldestPostId;
  DatabaseReference Dbref = FirebaseDatabase.getInstance().getReference("/event");


  /////GETTING FIRST 10 RECORDS FROM THE FIREBASE HERE

        Dbref.limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot child : dataSnapshot.getChildren()) {

                    oldestPostId = child.getKey(); ////HERE WE ARE SAVING THE LAST POST_ID FROM URS POST

                    dataSnapshot.getChildrenCount());
                    String event_id = snapshot.child("details").child("event_id").getValue().toString();
                    e=new Event(event_id); //Event is a model class for list items
                    event.add(e);
                    Log.e("ShowEventInfo : ", "" + event_id);
                }      
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

From above code , i have get the first 10 records from firebase, Now we will implement load more functionality so i am using the Listview's onscrolllistener On isScrollCompleted() we will use orderByKey() for getting further 10 more record with limitToFirst() method. I have implemented the whole code to get further data on isScrollCompleted() , please check below example.

YOUR_LISTVIEW.setOnScrollListener(new OnScrollListener() {
    private int currentVisibleItemCount;
    private int currentScrollState;
    private int currentFirstVisibleItem;
    private int totalItem;
    private LinearLayout lBelow;


    @Override
    public void onScrollStateChanged (AbsListView view,int scrollState){
        // TODO Auto-generated method stub
        this.currentScrollState = scrollState;
        this.isScrollCompleted();
    }

    @Override
    public void onScroll (AbsListView view,int firstVisibleItem,
    int visibleItemCount, int totalItemCount){
        // TODO Auto-generated method stub
        this.currentFirstVisibleItem = firstVisibleItem;
        this.currentVisibleItemCount = visibleItemCount;
        this.totalItem = totalItemCount;


    }

    private void isScrollCompleted () {
        if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
                && this.currentScrollState == SCROLL_STATE_IDLE) {
            /** To do code here*/
            Dbref.orderByKey().startAt(oldestPostId).limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot child : dataSnapshot.getChildren()) {

                        oldestPostId = child.getKey();
                        String event_id = snapshot.child("details").child("event_id").getValue().toString();
                        e = new Event(event_id); //Event is a model class for list items
                        event.add(e);
                        Log.e("ShowEventInfo : ", "" + event_id);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

        }
    });

});
Plusch answered 28/6, 2017 at 7:48 Comment(12)
Thanks for help but I have already solved it. Though it is similar what i have done!! Thanks again! :)Brilliancy
Now can you please remove duplicate flag....Brilliancy
@AnujKumar removed... Happy coding.. :)Plusch
It is marked as duplicate.. can i do something to undo this?Brilliancy
No brother u can not... It was marked by community, not by me..U can edit the question and than it can be undo...And do not afraid from this man..Keep happy coding...Here on SO each question and answer is reviewed by community member, they have all right to do with it..If they found any thing wrong corrosponding the question/answerPlusch
thanks its working very fineMadelainemadeleine
@Madelainemadeleine Welcome..Keep happy coding :)Plusch
@RavindraKushwaha Also, I was trying to save the scroll state of the above recyclerview. I tried retaining fragment state but didn't solve the issue. Any suggestions would be helpful :)Trawler
@YashLadia On above solution i have used the LIstview as the questioner was using it..I did not get..Please elaborate it morePlusch
Thanks so much for this !Hexamerous
@GastónSaillén happy to help you bro :)Plusch
@RavindraKushwaha everytime it is loading oldestPostId record even there is no more records in Firebase database, Any solution?Watchband

© 2022 - 2024 — McMap. All rights reserved.