Ahmed Imam
Ahmed Imam

Reputation: 1358

Sorting Data in Firebase

I'm using Firebase listview at its shown below and its working like a charm but the problem is it displays the last pushed key in the child("Posts") at the end of my listview(lv) I want the last pushed key to be displayed above all or if i can sort it by date.

    query = ref.child("Posts").orderByKey();
    FirebaseListAdapter<ChatRoomJ> adapter = new FirebaseListAdapter<ChatRoomJ>(
            ChatRoom.this,
            ChatRoomJ.class,
            R.layout.lvchatroom,query
    ) {
        @Override
        protected void populateView(View v, ChatRoomJ model, final int position) {

            final String date = model.getDate();
            final String displayName = model.getDisplayName();

            ((TextView) v.findViewById(R.id.displayname)).setText(displayName);
            ((TextView) v.findViewById(R.id.datel)).setText(date);


            });

        }
    };
    lv.setAdapter(adapter);

Upvotes: 4

Views: 2112

Answers (1)

Ryan
Ryan

Reputation: 2008

Method 1:

There is no way to reorder the data with your current code, unless you make your own class that extends FirebaseListAdapter and override the getItem() method. This is a great and easy way to do it (courtesy of Monet_z_Polski). I used the same trick with perfect results so far.

public abstract class ReverseFirebaseListAdapter<T> extends FirebaseListAdapter<T>  {

public ReverseFirebaseListAdapter(Activity activity, Class<T> modelClass, int modelLayout, Query ref) {
    super(activity, modelClass, modelLayout, ref);
}

public ReverseFirebaseListAdapter(Activity activity, Class<T> modelClass, int modelLayout, DatabaseReference ref) {
    super(activity, modelClass, modelLayout, ref);
}

@Override
public T getItem(int position) {
  return super.getItem(getCount() - (position + 1));
}

Then when you make the adapter, you use your new custom class that modifies the starting position for each item that is sent to the list.

Method 2:

The other way would be to read the data in to your app (probably into an ArrayList or something like that) and reorder the data on the client before populating the list with the properly ordered data. This can be as easy as reading the data into the ArrayList with a start index of 0 for each item. Something like chatRoomList.add(0, nextChatRoom); for example. That way when you populate the list on the screen it will be in the order you want.

There are other methods involving making a custom adapter, but I personally think that would be more complicated than these two methods. The first is my favorite.

Upvotes: 2

Related Questions