Firebase Data Desc Sorting in Android

前端 未结 15 2176
醉话见心
醉话见心 2020-11-22 07:51

I am storing data in Firebase storage.

Object Comment with attribute timestamp. When I push data from device to Firebase I\'m populating

相关标签:
15条回答
  • 2020-11-22 08:31

    You can simply just reverse the list (ListView or RecyclerView) that you are using.

    0 讨论(0)
  • 2020-11-22 08:32

    Sort at client side is simple and not require more system resources. Each data snapshot has previousChildkey field. If you want to desc sorting, imagine previousChildkey is nextChildKey. Here are my sample:

    class LessonFirebaseArray<ObjectModel>{
    
      private ArrayList<ObjectModel> mItems;
      ...
      public LessonFirebaseArray() {
        mItems = new ArrayList<>();
      }
    
      public int addItem(ObjectModel item, boolean isReverse){
        int index;
        if (item.getPreviousChildKey() != null) {
          index = getIndexForKey(item.getPreviousChildKey());
          if (index < 0) {
            index = mItems.size();
          }else if(index>0 && !isReverse) {
            index = index + 1;      
          }
        }else{
          index = mItems.size();
        }
        mItems.add(index, item);
        notifyInsertedListeners(index);
        return index;
      }
    
      private int getIndexForKey(String key) {
        int index = 0;
        for (ObjectModel snapshot : mItems) {
          if (snapshot.getKey().equals(key)) {
             return index;
          } else {
             index++;
          }
        }
        return -1;
      }
    
      private void notifyInsertedListeners(int index) {
        if (mListener != null) {
          mListener.onInserted(index);
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 08:32

    Sorting child items by TIMESTAMP can be done using android.support.v7.util.SortedList

      class post{
    private Object time; 
    
    public Object getTime() {
            return time;
        }
    
    public void setTime(Object time) {
        this.time = time;
    }
                            ...//rest code}
    
    SortedList<post> data;
    
     data = new SortedList<post>(post.class, new SortedList.Callback<post>() {
            @Override
            public int compare(post o1, post o2) {
                Long o1l = Long.parseLong(o1.getTime().toString());
                Long o2l = Long.parseLong(o2.getTime().toString());
    
                return o2l.compareTo(o1l);
            }......//rest code
    
    
    ref.addChildEventListener(new ChildEventListener() {
                  @Override
                  public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                     mSwipeRefreshLayout.setRefreshing(true);
                      post p=dataSnapshot.getValue(post.class);
    
    
                      data.add(p);
    
    
    
                  }...// rest code
    

    android.support.v7.util.SortedList can also be used with RecyclerView

    0 讨论(0)
提交回复
热议问题