簡體   English   中英

Android Event contentResolver查詢同步問題

[英]Android Event contentResolver query synchronize problem

我正在使用以下代碼從核心事件日歷應用程序中提取數據以顯示在我的應用程序中。

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

該代碼工作正常。 但是有時候,如果我在日歷中添加事件並返回到應用程序,則不會顯示新事件。 如果我退出該應用程序,然后再次返回或更改選項卡,則新事件將添加到列表中。 有什么要解決的同步?

日歷添加完成后返回應用程序時,將調用onResume()。 在此處重新查詢光標,以更新您的UI。

另外,您應該查看ContentObserver界面,該界面設置了一個回調界面,用於通知更改(例如,在您完全沒有離開應用程序的情況下,網絡同步后它們會顯示在設備上。)

最后,使用CursorAdapter從您的Cursor驅動ListView將自動設置ContentObserver並處理為達到這一目的而必須編寫的大量粘合代碼。 這是一種更加自動化的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM