如何从Firebase数据库中基于时间戳获取排序的数据

时间:2019-06-01 17:54:08

标签: java android firebase firebase-realtime-database android-recyclerview

在我的Firebase数据库中,我正在存储这样的数据

pic 1

pic 2

现在,我想根据时间戳从Firebase实时数据库中以RecyclerView的降序/最新顺序检索并显示数据。

我尝试了layoutmanager.setReverseLayout(true);,     layoutmanager.setStackFromEnd(true);用于反转RecyclerView,但它总是显示来自中间的数据,而且我也不想遵循这种方法。 由于我将所有数据添加到ArrayList resultsHistory中。现在如何根据最新时间戳对Arraylist进行排序,然后设置适配器?它能解决问题吗?

下面是我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_history);

    customerOrDriver = getIntent().getExtras().getString("customerOrDriver");
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(HistoryActivity.this);

    userId = sharedPreferences.getString("UID", "");

    mHistoryRecyclerView = (RecyclerView) findViewById(R.id.historyRecyclerView);

    //mHistoryAdapter = new HistoryAdapter(getDataSetHistory(), HistoryActivity.this);
    mHistoryLayoutManager = new LinearLayoutManager(HistoryActivity.this);
    mHistoryRecyclerView.setLayoutManager(mHistoryLayoutManager);
    mHistoryRecyclerView.setHasFixedSize(true);
    /*// sort the recycler view to descending order
    ((LinearLayoutManager) mHistoryLayoutManager).setReverseLayout(true);
    ((LinearLayoutManager) mHistoryLayoutManager).setStackFromEnd(true);*/
    mHistoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mHistoryRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    // mHistoryRecyclerView.setAdapter(mHistoryAdapter);

    getUserHistoryIds();
}

private void getUserHistoryIds() {
    //swipeRefreshLayout.setRefreshing(true);
    DatabaseReference userHistoryDatabase = FirebaseDatabase.getInstance().getReference().child(Common.user_table).child(customerOrDriver).child(userId).child(Common.history_table);
    userHistoryDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot history : dataSnapshot.getChildren()) {
                    FetchRideInformation(history.getKey());
                    //swipeRefreshLayout.setRefreshing(false);
                }
                sortDate();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            //swipeRefreshLayout.setRefreshing(false);
        }
    });
}

private void FetchRideInformation(String rideKey) {
    DatabaseReference historyDatabase = FirebaseDatabase.getInstance().getReference().child(Common.history_table).child(rideKey);
    historyDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                String rideId = dataSnapshot.getKey();
                timestamp = 0L;
                for (DataSnapshot child : dataSnapshot.getChildren()) {
                    if (child.getKey().equals("timestamp")) {
                        timestamp = Long.valueOf(child.getValue().toString());
                    }
                }
                getRideInformation(rideId, timestamp);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

private void getRideInformation(final String rideId, final Long timestamp) {
    DatabaseReference historyRideInfoDb = FirebaseDatabase.getInstance().getReference().child(Common.history_table).child(rideId);
    historyRideInfoDb.addListenerForSingleValueEvent(new ValueEventListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot child : dataSnapshot.getChildren()) {
                    if (child.getKey().equals("patient")) {
                        patientId = child.getValue().toString();
                        if (!patientId.equals(userId)) {
                            userDriverOrCustomer = "Doctors";
                            getUserInformation("Patients", patientId, rideId, timestamp);
                        }
                    } else if (child.getKey().equals("patient")) {
                        patientId = child.getValue().toString();
                        if (!patientId.equals(userId)) {
                            userDriverOrCustomer = "Phamacys";
                            getUserInformation("Patients", patientId, rideId, timestamp);
                        }
                    }
                    if (child.getKey().equals("doctor")) {
                        doctorId = child.getValue().toString();
                        if (!doctorId.equals(userId)) {
                            userDriverOrCustomer = "Patients";
                            getUserInformation("Doctors", doctorId, rideId, timestamp);
                        }
                    } else if (child.getKey().equals("pharmacy")) {
                        pharmacyId = child.getValue().toString();
                        if (!pharmacyId.equals(userId)) {
                            userDriverOrCustomer = "Patients";
                            getUserInformation("Pharmacys", pharmacyId, rideId, timestamp);
                        }
                    }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

private void getUserInformation(String otherUserDriverOrCustomer, String otherUserId, final String rideId, final Long timestamp) {
    DatabaseReference mOtherUserDB = FirebaseDatabase.getInstance().getReference().child(Common.user_table).child(otherUserDriverOrCustomer).child(otherUserId);
    mOtherUserDB.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                if (map.get("name") != null) {
                    name = (map.get("name").toString());
                }
                if (map.get("service") == null) {
                    service = (map.get("phone").toString());
                } else if (map.get("service") != null) {
                    service = (map.get("service").toString());
                }

                HistoryObject obj = new HistoryObject(rideId, name, service, getDate(timestamp), timestamp);
                resultsHistory.add(obj);
                mHistoryAdapter.notifyDataSetChanged();
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

private String getDate(Long time) {
    Calendar cal = Calendar.getInstance(Locale.getDefault());
    cal.setTimeInMillis(time * 1000);
    String date = DateFormat.format("MMMM dd yyyy, hh:mm a", cal).toString();
    return date;
}

private ArrayList<HistoryObject> resultsHistory = new ArrayList<HistoryObject>();

private ArrayList<HistoryObject> getDataSetHistory() {
    return resultsHistory;
}

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}


public void sortDate() {
    /*Collections.sort(resultsHistory, new Comparator<HistoryObject>() {
        DateFormat f = new SimpleDateFormat("MMMM dd yyyy, hh:mm a");
        @Override
        public int compare(HistoryObject lhs, HistoryObject rhs) {
            try {
                return f.parse(lhs.getTime()).compareTo(f.parse(rhs.getTime()));
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
        }
    });*/
    Collections.sort(resultsHistory, new Comparator<HistoryObject>() {
        public int compare(HistoryObject o1, HistoryObject o2) {
            if (o1.getT() == null || o2.getT() == null)
                return 0;
            return o2.getT().compareTo(o1.getT());
        }
    });
    mHistoryAdapter = new HistoryAdapter(resultsHistory, HistoryActivity.this);
    mHistoryRecyclerView.setAdapter(mHistoryAdapter);
}

1 个答案:

答案 0 :(得分:0)

Ref:https://firebase.google.com/docs/database/android/lists-of-data

排序数据

要检索排序的数据,请先指定一种排序方法来确定结果的排序方式:

orderByChild()

  

通过指定的子关键字或嵌套的子路径的值对结果进行排序。

orderByKey()

  

通过子键订购结果。

orderByValue()

  

按子值对结果进行排序。