Sorting Data in Firebase

送分小仙女□ 提交于 2019-12-10 09:33:38

问题


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);

回答1:


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.



来源:https://stackoverflow.com/questions/39885657/sorting-data-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!