提取Android后如何对List <Model>数据进行排序

时间:2019-06-02 09:18:48

标签: java android android-recyclerview

我正在获取数据并将其从Firebase数据库添加到列表中。 现在,我想根据时间对列表数据进行排序,以便最新数据将首先出现在列表中,然后将更新后的列表设置到我的RecyclerView.Adapter中。我已经尝试过layoutmanager.setReverseLayout(true);layoutmanager.setStackFromEnd(true);来反转RecyclerView,但它总是显示来自中间的数据,而且我也不想遵循这种方法。 我该怎么办。

public class HistoryActivity extends AppCompatActivity{
private String customerOrDriver, userId;
private String doctorId, patientId, pharmacyId, userDriverOrCustomer;
private Long timestamp;
private String name, service;

private SwipeRefreshLayout swipeRefreshLayout;

private RecyclerView mHistoryRecyclerView;
private RecyclerView.Adapter mHistoryAdapter;
private RecyclerView.LayoutManager mHistoryLayoutManager;
SharedPreferences sharedPreferences;

@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);
                }
            }
        }
        @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));
                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 resultsHistory = new ArrayList<HistoryObject>();
private ArrayList<HistoryObject> getDataSetHistory() {

    return resultsHistory;
}

}

2 个答案:

答案 0 :(得分:0)

只需使用myList.sort(),然后按照需要的方式进行阅读,例如将其升序或降序并将其放入RecyclerView

答案 1 :(得分:0)

您可以按照以下方式进行排序

我刚刚向您展示了一个Student对象,但您可以使用datetime进行检查

使用Lambda表达式:使用Lambda表达式的Java 8等效代码如下所示:

studentlist.sort((Student s1, Student s2)->s1.getName().compareTo(s2.getName()));