2013-03-24 51 views
3

我想以編程方式將事件添加到用戶的日曆。我已經在StackOverflow和其他地方跟隨了無數的指南,但是他們都不會讓這個該死的事件出現在我的日曆中。這裏是我當前的代碼:將事件添加到android日曆失敗

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()方法。此方法顯示一個帶有用戶日曆列表的標準對話框,當用戶選擇其中一個日曆時,將使用所選日曆的ID作爲參數調用loopThroughGames()方法。這種方法將在所有工作正常時將所有用戶的遊戲寫入日曆,但出於測試目的,它只寫入一個。 addGameToCalendar()方法需要一個遊戲對象,該對象包含諸如時間,標題,位置,日期等很多值,並使用Web上許多不同位置中概述的標準方式將其插入到日曆中。

我沒有收到此代碼的錯誤消息(除了我自己發送給錯誤日誌的錯誤消息),所以我不知道爲什麼這段代碼無法正常工作。沒有錯誤,只是遊戲永遠不會出現在我的日曆中。我在清單中正確設置了權限,所以我知道這不是問題。

有沒有人有解決這個惱人的問題?謝謝你的幫助!

回答

6

[RE-EDIT] 這是我做的,它就像一個魅力..

  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(); 
     } 
+0

你測試了什麼API級別。我在API 17(android 4.2)上運行這個代碼,並沒有奏效。 calNames滿了null,calId滿了0。我認爲這種方式不適用於更新版本的Android,API 14之後。 – TheMasster12 2013-03-28 18:00:16

+0

哦,對不起,我修改了代碼,它現在應該可以正常工作:) – user788511 2013-03-29 10:19:49

+0

我在我的果凍豆設備上進行了測試,它的工作正常。 – user788511 2013-03-29 10:24:23

0

保護無效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); 
} 
-2

這個工作而且更容易瞭解:

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