0

我正在使用以下代码从核心事件日历应用程序中提取数据以显示在我的应用程序中。

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);
    }
}

代码工作正常。但有时如果我在日历中添加一个事件并返回应用程序,它不会显示新事件。如果我退出应用程序并再次返回或更改选项卡,则新事件将添加到列表中。有什么办法解决同步问题?

4

1 回答 1

1

当您在添加日历后返回您的应用程序时,会调用 onResume()。在那里重新查询光标以使您的 UI 更新。

此外,您应该查看 ContentObserver 接口,该接口设置了一个回调接口,用于通知更改(假设它们在网络同步后显示在设备上,而您根本没有离开您的应用程序。)

最后,使用 CursorAdapter 从 Cursor 驱动 ListView 将自动设置 ContentObserver 并处理您必须编写的大量胶水代码才能达到此目的。这是一种更加自动化的方式。

于 2011-04-10T19:11:13.720 回答