【问题标题】:Adding events to android calendar failing将事件添加到 android 日历失败
【发布时间】:2014-01-31 11:35:05
【问题描述】:

我正在尝试以编程方式将事件添加到用户的日历中。我在 StackOverflow 和其他地方遵循了无数指南,但没有一个能让该死的事件出现在我的日历中。这是我当前的代码:

public void saveGamesToCalendar() {
    showCalendarPopup();
}

private void showCalendarPopup() {
    final ContentResolver cr;
    final Cursor result;
    final Uri uri;
    List<String> listCals = new ArrayList<String>();
    final String[] projection = new String[] {CalendarContract.Calendars._ID, CalendarContract.Calendars.ACCOUNT_NAME, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, CalendarContract.Calendars.NAME,};

    uri = CalendarContract.Calendars.CONTENT_URI;

    cr = context.getContentResolver();
    result = cr.query(uri, projection, null, null, null);
    if(result.getCount() > 0 && result.moveToFirst()) {
        do {
                listCals.add(result.getString(result.getColumnIndex(CalendarContract.Calendars.NAME)));
    } while(result.moveToNext());
}
CharSequence[] calendars = listCals.toArray(new CharSequence[listCals.size()]);

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Calendar to use:");
builder.setItems(calendars, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog,int itemCal) {
            Log.e("SettingsActivity", "CalendarID: " + itemCal);
            loopThroughGames(itemCal);
        };
    });
    AlertDialog alert = builder.create();
    alert.show();
}

private void loopThroughGames(int whichCalendar) {
    ArrayList<Model_Game> games = memoryManager.getGames();

    // for(Game e: games)
    Log.e("Game", games.get(101).toString());
    addGameToCalendar(games.get(101), whichCalendar);

    Log.e("ID", "" + whichCalendar);
}

private void addGameToCalendar(Model_Game game,int whichCalendar) {
    ContentResolver cr = context.getContentResolver();
    ContentValues values = new ContentValues();

    try {
        values.put(CalendarContract.Events.CALENDAR_ID, whichCalendar);
        values.put(CalendarContract.Events.TITLE, "Hockey- " + game.getLeague() + ": " + game.getTeamH() + " vs " + game.getTeamA());
        values.put(CalendarContract.Events.EVENT_LOCATION, "Twin Rinks Ice Arena- " + game.getRink() + " Rink");
        values.put(CalendarContract.Events.DTSTART, "" + game.getCalendarObject().getTimeInMillis());
        //values.put(CalendarContract.Events.DTEND, "" + game.getCalendarObject().getTimeInMillis() + 5400000);
        values.put(CalendarContract.Events.DURATION, "" + 5400000);
        values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());

        cr.insert(CalendarContract.Events.CONTENT_URI, values);
    } catch(Exception e) {
        Log.e("Error", e.getMessage());
        toast(e.getMessage());
    }
}

基本上发生的事情是用户按下操作栏按钮,该按钮调用saveGamesToCalendar() 方法,该方法调用ShowCalendarPopup() 方法。此方法显示一个包含用户日历列表的标准对话框,当用户选择其中一个时,将调用 loopThroughGames() 方法,并将所选日历的 ID 作为参数。当一切正常时,此方法会将用户的所有游戏写入日历,但出于测试目的,它只写入一个。 addGameToCalendar() 方法接受一个游戏对象,该对象包含许多值,如时间、标题、位置、日期等,并使用网络上许多不同地方概述的标准方式将其插入日历中。

我没有收到有关此代码的错误消息(除了我自己发送到错误日志的错误消息),所以我不知道为什么此代码不起作用。没有错误,只是游戏从未出现在我的日历中。我在清单中正确设置了权限,所以我知道这不是问题。

有没有人能解决这个烦人的问题?感谢您的帮助!

【问题讨论】:

    标签: android calendar android-contentresolver android-cursor


    【解决方案1】:

    [重新编辑]] 这就是我所做的,它就像一个魅力..

             Cursor cursor = null ;
    
             String[] projection = new String[] {
                       CalendarContract.Calendars._ID,
                       CalendarContract.Calendars.ACCOUNT_NAME,};
    
             ContentResolver cr = context2.getContentResolver();
             cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection, null, null, null);
    
             if ( cursor.moveToFirst() ) {
                    final String[] calNames = new String[cursor.getCount()];
                    calIds = new int[cursor.getCount()];
                    for (int i = 0; i < calNames.length; i++) {
                        calIds[i] = cursor.getInt(0);
                        calNames[i] = cursor.getString(1);
                        cursor.moveToNext();
                    }
                }
    
            try {           
    
                ContentValues values = new ContentValues();
    
    //          int apiLevel = android.os.Build.VERSION.SDK_INT;
    //            if(apiLevel<14){
    //              values.put("visibility", 0);
    //
    //            }
                values.put(Events.DTSTART, stTime);
                values.put(Events.DTEND, enTime);
                values.put(Events.TITLE, category);
                values.put(Events.DESCRIPTION, description);
                values.put(Events.CALENDAR_ID, calIds[0]);
                values.put(Events.EVENT_LOCATION,place);
                values.put(Events.EVENT_TIMEZONE,tZone);
    
                mInsert =  cr.insert(CalendarContract.Events.CONTENT_URI, values);
    
                Toast.makeText(context2, "Event added Successfully",
                        Toast.LENGTH_LONG).show();
    
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(context2, "Exception: " + e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
    

    【讨论】:

    • 你在什么 API 级别上测试过这个。我在 API 17 (android 4.2) 上运行了这段代码,但它没有用。 calNames 中充满了 null,而 calIds 中充满了 0。我认为这种方式不适用于 API 14 之后的较新版本的 Android。
    • 抱歉,我已经修改了代码,现在应该可以正常工作了 :)
    【解决方案2】:

    受保护的 void eventAdding() {

        try
        {
            Calendar beginTime = Calendar.getInstance();
            beginTime.set(2013, 11, 20, 8,0 );
            startMillis = beginTime.getTimeInMillis();
            Calendar endTime = Calendar.getInstance();
            endTime.set(2013, 11, 20, 8, 50);
            endMillis = endTime.getTimeInMillis();
    
    
    
    
          ContentResolver cr = this.getContentResolver();
          ContentValues values = new ContentValues();
    
          values.put(Events.DTSTART, startMillis);
          values.put(Events.DTEND, endMillis);
          values.put(Events.TITLE, "Hello");
    
          values.put(Events.CALENDAR_ID, 1);            
          values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
    
    
    if (android.os.Build.VERSION.SDK_INT <= 7) {
    
             uri = Uri.parse("content://calendar/events");
         } else 
         {
    
             uri = Uri.parse("content://com.android.calendar/events");
         }
          Uri urievent = cr.insert(uri, values);    
    
    
         } 
    catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    
           }
    
        //event = Utility.readCalendarEvent(CalnderEvent.this);
    }
    

    【讨论】:

      【解决方案3】:

      这很有效,而且更容易理解:

           long startTime = calSet.getTimeInMillis();
                 Intent intent = new Intent(Intent.ACTION_INSERT).setData(Events.CONTENT_URI)
                       .setData(Events.CONTENT_URI)
                      .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime)
                  .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, startTime + (length*3600000))
                      .putExtra(Events.TITLE, examName)
                      .putExtra(Events.EVENT_LOCATION, venue)
                      .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
                      .putExtra(Events.HAS_ALARM, 1);
      
                       startActivity(intent);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多