我有一个简单的类事件,我将其保存到一个SQlite数据库中,与活动的android一样:
Event.java
@Table(name = "events", id = "_id")
public class Event extends Model {
@Column (name = "EventLocation")
private String mEventLocation;
@Column (name = "EventDate")
private String mEventDate;
}
AddEventActivity.java:
mSubmitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String eventLocation = mEventLocation.getText().toString();
String eventDate = mEventDate.getText().toString();
Event event = new Event(eventLocation,eventDate);
event.save();
等。目前,我将日期以及开始/结束时间保存为字符串。但是我在我的应用程序中添加了一个新功能,我希望将当前日期/时间与我的ArrayList对象的日期进行比较,然后返回当天晚些时候或之后发生的下一个事件。
最有效的方法是什么?我需要能够使用Comparable或Comparator按日期对事件的ArrayList进行排序,然后将它们与当前日期进行比较,因此我尝试将字符串解析为Date对象和SimpleDateFormatter,但因为它们是字符串,所以不会真的有用。如何使用Active Android将日期保存到SQLite?我找到的所有保存例子都是字符串。
我是Java / Android的新手。非常感谢。
答案 0 :(得分:4)
1)对列表进行排序
制作Event
班级工具Comparable
。在compareTo()
方法中,使用Date
进行比较。
确保Date
课程中的dateTime类型为Event
。
public class Event extends Model implements Comparable{
...
@Override
public int compareTo(MyObject o) {
return getDateTime().compareTo(o.getDateTime());
}
}
或者,如果您不想更改模型,请立即创建Comparator
Collections.sort(myList, new Comparator<Event>() {
public int compare(Event o1, Event o2) {
if (o1.getDateTime() == null || o2.getDateTime() == null)
return 0;
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
2)将日期存储到ActiveAndroid
ActiveAndroid支持自动序列化日期字段。它在内部存储为时间戳(INTEGER),以毫秒为单位。
@Column(name = "timestamp", index = true)
private Date timestamp;
//and the date will be serialized to SQLite. You can parse strings into a Date object using SimpleDateFormat:
public void setDateFromString(String date) throws ParseException {
SimpleDateFormat sf = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy");
sf.setLenient(true);
this.timestamp = sf.parse(date);
}
或者您可以创建一个Util方法将String
转换为Date
,返回Date
:
public Date getDateFromString(String selectedDate) throws ParseException{
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(selectedDate);
return date;
}
3)将日期与事件对象列表进行比较。
然后最后调用函数从List
中查找指定日期之后的日期public static List<Event> findRecent(Date newerThan) {
return new Select().from(Event.class).where("timestamp > ?", newerThan.getTimeInMillis()).execute();
}
希望它有所帮助!