2011-03-22 94 views
0

我正在使用以下代碼從核心事件日曆應用程序中提取數據以顯示在我的應用程序中。Android事件contentResolver查詢同步問題

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

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

回答

1

當日歷添加發生後回到應用程序時,會調用onResume()。在那裏重新查詢光標以使您的UI更新。

另外,你應該看一下ContentObserver接口,該接口設置一個回調接口來通知更改(假設他們在網絡同步後顯示在設備上,而你根本沒有離開你的應用程序。)

最後,使用CursorAdapter從你的Cursor中驅動一個ListView將自動建立一個ContentObserver並且處理你必須編寫的很多膠水代碼以實現這一目標。這是一個更自動的方式。