问题描述
我正在尝试按日期对 arrayList
进行排序。我每次收到通知时都会将日期存储在Firebase上,并从那里检索。我正在使用 Collections.sort
但我不知道如何实现我的代码,因为我的日期格式以字符串格式的数字开头,如2017年7月12日at 12:00 AM。
I'm trying to sort my arrayList
by date. I stored the date on Firebase each time I receive a notification and is retrieved from there. I'm using Collections.sort
but I don't know how to implement onto my codes as my date format starts with a number in a string format like "12 Jul 2017 at 12:00am".
我在stackoverflow上看到了一些这样的例子,但我不知道如何让它在我的情况下工作。我将在下面发布截图和我的代码。
I've seen some examples of this on stackoverflow but I don't know how to make it work in my case. I will post screenshots and my codes below.
日期未排序。
NotificationFragment.java
public class NotificationFragment extends Fragment {
prepareNotification1();
sortDate();
return v;
}
private void prepareNotification1() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userID = user.getUid();
mRef.child("customers").child(userID).child("Notification").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Notification menu = dataSnapshot.getValue(Notification.class);
notificationList.add(menu);
mAdapter.notifyDataSetChanged();
}
});
}
public void sortDate() {
Collections.sort(notificationList, new Comparator<Notification>() {
@Override
public int compare(Notification lhs, Notification rhs) {
return lhs.getDate().compareTo(rhs.getDate());
}
});
mAdapter = new NotificationAdapter(getContext(), notificationList);
mRecyclerView.setAdapter(mAdapter);
}
}
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Calendar cal = Calendar.getInstance();
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
String currentTime = df.format(cal.getTime());
String notificationTime = currentDateTimeString + " at " + currentTime;
Notification newNotification = new Notification(remoteMessage.getData().get("body"), notificationTime);
mRef.child("customers").child(userID).child("Notification").push().setValue(newNotification);
}
Notification.java
public class Notification {
private String message;
private String date;
public Notification(){
}
public Notification(String message, String date){
this.message = message;
this.date = date;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
推荐答案
考虑将日期存储在通知
中作为长
(unix时间)或日期
( LocalDateTime
如果您正在使用Java 8支持)并仅在将其显示为UI时将其格式化为String。
Consider storing the date in Notification
as a long
(unix time) or a Date
(LocalDateTime
if you're using Java 8 support) and formatting it as a String only when displaying it to the UI.
这篇关于Android - 如何按日期对arrayList进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!