2

I m developing an app with Firebase database. I'm receiving data and uploading it there is no problem in that, but I want to add my data on the top of database array, not at the bottom of database array.

So suggest me something which can help me to retrieve the data from bottom to the top or I can upload it to the top of my database array. Thanks in advance. Please help me out.

AL.
  • 36,815
  • 10
  • 142
  • 281
sam
  • 216
  • 4
  • 17

2 Answers2

8

There's a couple ways to do this.

First:

Implement FirebaseUI and then do the following:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager)

Second:

I prefer this way, especially if you plan to implement a GridLayoutManager in the future. Note, GridLayoutManager does not support setStackFromEnd();. The below will allow you to reverse any data in an `AdapterView.

In your RecyclerViewAdapter

@Override
public Item getItem(int pos) {
return super.getItem(getCount() - 1 - pos);
}
Drew Szurko
  • 1,601
  • 1
  • 16
  • 32
  • yeah, m working with **GridLayoutManager** with **FirebaseRecyclerAdapter** . can u explain how to put this code??? and how to declare **Item**. m newbie to android firebase...!! – sam Feb 22 '17 at 17:33
  • It's really impossible without your original post having your code. Are you at least displaying data from Firebase, you just need it in reverse order? – Drew Szurko Feb 22 '17 at 17:51
  • I just want to reverse the data. – sam Feb 22 '17 at 18:09
  • I just want to retrieve the last added data at first position then second last and so on. – sam Feb 22 '17 at 18:13
  • I'm still having trouble understanding... are you already getting data from Firebase and just want to reverse it, because that's what your original post sounds like.. Or are you not retrieving data yet? If you are not retrieving data yet, then you should refer to one of [these](http://stackoverflow.com/search?q=%5Bandroid%5Dhow+to+get+data+from+firebase) posts on "how to get data from firebase". This post answers your original question on how to get Firebase data in descending order, so if you have a chance, please accept it. – Drew Szurko Feb 22 '17 at 19:24
  • dude, sorry i miss understands you. your second method works thanks alot. u just saved my life – sam Feb 24 '17 at 05:31
0

It is very easy. Use the firebase query like this:

Query dbRef = FirebaseDatabase.instance.reference().child("Post")
                .orderByKey()
                .limitToLast(5)
                .endAt(endKey);

The end key is the last end of your data. That is the last key where the retrieved data is stoped. After retrieving the first five items you can get a new endKey and pass the end key. It retrieves data from top to bottom.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93