Android Event contentResolver query synchronize problem
I am using following code to pull the data from the core event calendar application to show in my app.
ContentResolver contentResolver = this.getContentResolver();
f开发者_JAVA百科inal 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);
}
}
The code is working fine. But sometime if I add a event in the calendar and come back to app, it is not showing the new event. If i exit the app and again come back or change the tab, the new event is added to the list. What have to do solve the synchronize?
When you come back to your app after the calendar add occurs, onResume() gets called. Re-query the cursor there to cause your UI to update.
Also, you should look at the ContentObserver interface, which sets up a callback interface for being notified of changes (Say they show up on the device after a network sync while you haven't left your app at all.)
Finally, using a CursorAdapter to drive a ListView from your Cursor will set up a ContentObserver automatically and take care of a lot of the glue code you had to write to get this far. It's a much more automatic way of doing it.
精彩评论