我正在使用以下代码从核心事件日历应用程序中提取数据以显示在我的应用中。
ContentResolver contentResolver = this.getContentResolver();
final Cursor cursor = contentResolver.query(Uri.parse("content://calendar/calendars"),(new String[] { "_id", "displayName", "selected" }),null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Boolean selected = !cursor.getString(2).equals("0");
calendarIds.add(_id);
}
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse(
"content://calendar/instances/when").buildUpon();
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
ContentUris.appendId(builder, now
- ((DateUtils.DAY_IN_MILLIS) * 24));
ContentUris.appendId(builder, now
+ ((DateUtils.DAY_IN_MILLIS) * 24));
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay",
"description", "eventLocation", "dtstart",
"dtend", "eventStatus", "visibility",
"transparency", "hasAlarm" },
"Calendars._id=" + id, null,
"startDay ASC, startMinute ASC");
while (eventCursor.moveToNext()) {
if (eventCursor != null) {
String title = eventCursor.getString(0);
}
}
代码运行正常。但有时如果我在日历中添加一个事件并回到应用程序,它就不会显示新事件。如果我退出应用程序并再次返回或更改选项卡,则新事件将添加到列表中。要解决同步问题需要做什么?
答案 0 :(得分:1)
在日历添加发生后返回应用程序时,会调用onResume()。在那里重新查询光标以使UI更新。
此外,您应该查看ContentObserver接口,该接口设置一个回调接口以通知更改(假设您在完全没有离开应用程序时在网络同步后显示在设备上。)
最后,使用CursorAdapter从Cursor驱动ListView将自动设置ContentObserver并处理您必须编写的许多粘合代码以实现这一目标。这是一种更自动化的方式。