-2

I have a data base reference and in that I have the details of the announcement, but actually when a new announcement is added to the existing database, it gets displayed way below the last element, I want it to be on the top.

Here is the code for reading announcement from DB

 demo= FirebaseDatabase.getInstance().getReference().child("IDS").child("/News");


    demo.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                RvClass rvClass = snapshot.getValue(RvClass.class);
                list.add(rvClass);

            }
            CustomAdapter adapter = new CustomAdapter(SubmitNews.this,list);
            rv.setAdapter(adapter);

        }


       @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

After fetching the data I displayed it in a RecyclerView , all functionality is fine except the newly added announcement, it is getting placed at the last.

Thank you!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Searching for [firebase android newest on top](https://www.google.com/search?q=site:stackoverflow.com+firebase+android+newest+on+top) gives some good results. Most seem based around reversing the layout manager and stacking it from the top as shown here: https://stackoverflow.com/a/43321791/209103 – Frank van Puffelen Jun 26 '18 at 14:00

1 Answers1

0

You can do it using limitToLast()
Example of limitToLast()

  demo = FirebaseDatabase.getInstance().getReference().child("IDS").child("/News");
     Query query = demo.orderByKey().limitToLast(15);
     query.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        RvClass rvClass = snapshot.getValue(RvClass.class);
                        list.add(rvClass);

                    }
                    CustomAdapter adapter = new CustomAdapter(SubmitNews.this, list);
                    rv.setAdapter(adapter);

                }


                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

Also please check below link this will help you.
Firebase Data Desc Sorting in Android

Dhaval Solanki
  • 4,589
  • 1
  • 23
  • 39