Calendar Provider批量插入

时间:2012-12-05 08:50:53

标签: android android-calendar

您好我正在尝试通过批量插入向Calendar Provider插入几个日历事件。我的代码失败,出现IllegalArgumentException

 private void synchronizeCalendar(long calID){
    TLApplication.getDB().getDB().beginTransaction();
    try {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        TLCalendar calendar = TLApplication.getDB().loadCalendar();
        if(calendar.days!=null && calendar.days.size()> 0){
            for (TLDay day : calendar.days) {
                for (TLEvent event : day.events) {
                    List<TLComponent> comps = TLApplication.getDB().loadComponents(event.cid);
                    if(comps.size()>0){
                        TLComponent comp = comps.get(0);
                        //new batch operation
                        ops.add(ContentProviderOperation.newInsert(getCalendarUri())
                                .withValue(Events.DTSTART, getStartDate(event, comp)) //long
                                .withValue(Events.DTEND, getEndDate(event, comp)) //long
                                .withValue(Events.TITLE, getTitle(event)) //String
                                .withValue(Events.EVENT_LOCATION, getLocation(event)) //String
                                .withValue(Events.DESCRIPTION, getNotes(comp)) //String
                                .withValue(Events.CALENDAR_ID, calID) //long
                                .withValue(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID()) //String
                                .build());
                    }
                }
            }
            if(ops.size() > 0){
                ContentResolver cr = ctx.getContentResolver();
                ContentProviderResult[] results = cr.applyBatch(CalendarContract.AUTHORITY, ops);
                for (ContentProviderResult result : results) {
                    Log.v(TAG, "addBatchEvent: " + result.uri.toString());
                }
            }else{
                Log.w(TAG, "No batch operations found! Do nothing");
            }
        }

    }catch (Exception e) {
        Log.e(TAG, "synchronizeCalendar", e);

    } finally{
        TLApplication.getDB().getDB().endTransaction();
    }
}

例外情况是: java.lang.IllegalArgumentException:列'calendar_id'无效

此代码的模式是来自sdk的“ContactManager”示例: docs / resources / samples / ContactManager / src / com / example / android / contactmanager / ContactAdder.html

是否有人有批量插入日历的经验?我是否需要实施Sync Adapter

1 个答案:

答案 0 :(得分:1)

在我的实现中发现了错误。我已使用getCalendarUri()获取Calendars.CONTENT_URI,但我必须使用Events.CONTENT_URI来表示事件。