我有一个简单的类事件,我将它保存到一个带有 Activity android 的 SQlite 数据库中,如下所示:
事件.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 的新手。非常感谢。
最佳答案
1) 列表排序
让您的Event
类实现Comparable
。在 compareTo()
方法中,使用 Date
进行比较。
确保 dateTime 的类型是Event
类中的Date
。
public class Event extends Model implements Comparable{
...
@Override
public int compareTo(MyObject o) {
return getDateTime().compareTo(o.getDateTime());
}
}
或者,如果你不想改变你的模型,即时创建比较器
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();
}
希望对您有所帮助!
关于java - 使用 Active Android 将日期保存到 sqlite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33600001/