2013-04-26 11 views
8

カレンダーに予定を追加するためのコードは次のとおりです。AndroidでデフォルトのカレンダーIDを取得する

問題は、のデフォルトのカレンダーIDを取得する方法がわかりません。

long calID = 3; 
long startMillis = 0; 
long endMillis = 0;  
Calendar beginTime = Calendar.getInstance(); 
beginTime.set(2013, 3, 23, 7, 30); 
startMillis = beginTime.getTimeInMillis(); 
Calendar endTime = Calendar.getInstance(); 
endTime.set(2013, 3, 24, 8, 45); 
endMillis = endTime.getTimeInMillis(); 

ContentResolver cr = getContentResolver(); 
ContentValues values = new ContentValues(); 
values.put(Events.DTSTART, startMillis); 
values.put(Events.DTEND, endMillis); 
values.put(Events.TITLE, "My Test"); 
values.put(Events.DESCRIPTION, "My Calendar Test"); 
values.put(Events.CALENDAR_ID, calID); 
values.put(Events.EVENT_TIMEZONE, "Israel/tel-aviv"); 
Uri uri = cr.insert(Events.CONTENT_URI, values); 

ライン:long calID = 3;はカレンダーID

は、AndroidからのデフォルトのカレンダーIDを取得することが可能です、または私はカレンダーのリストを表示し、ユーザーが1つを選ぶ持っている必要がありますでしょうか?

できない場合は、カレンダーアカウントのリストを表示するにはどうすればよいですか?

答えて

11

カレンダーのリストを取得するには、次のようなContentResolverのを照会する必要があります。

public MyCalendar [] getCalendar(Context c) { 

    String projection[] = {"_id", "calendar_displayName"}; 
    Uri calendars; 
    calendars = Uri.parse("content://com.android.calendar/calendars"); 

    ContentResolver contentResolver = c.getContentResolver(); 
    Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null); 

    if (managedCursor.moveToFirst()){ 
     m_calendars = new MyCalendar[managedCursor.getCount()]; 
     String calName; 
     String calID; 
     int cont= 0; 
     int nameCol = managedCursor.getColumnIndex(projection[1]); 
     int idCol = managedCursor.getColumnIndex(projection[0]); 
     do { 
      calName = managedCursor.getString(nameCol); 
      calID = managedCursor.getString(idCol); 
      m_calendars[cont] = new MyCalendar(calName, calID); 
      cont++; 
     } while(managedCursor.moveToNext()); 
     managedCursor.close(); 
    } 
    return m_calendars; 

} 
5

CalendarContract.CalendarColumnsIS_PRIMARY列があります。あなたは選択して照会:一部の最新バージョンでは問題がある

2

SDK 17以降

CalendarContract.CalendarColumns.IS_PRIMARY + "=1" 

しかし、これは、このクエリが異なる表示カレンダーリストはとても以下であるPRIMARYカレンダーを選択するためのコードで、古いデバイスで0レコードを返すので、1レコード目が0レコードを返す場合は2レコード目を使用します。

Cursor calCursor = mContext.getContentResolver().query(CalendarContract.Calendars.CONTENT_URI, projection, CalendarContract.Calendars.VISIBLE + " = 1 AND " + CalendarContract.Calendars.IS_PRIMARY + "=1", null, CalendarContract.Calendars._ID + " ASC"); 
if(calCursor.getCount() <= 0){ 
    calCursor = mContext.getContentResolver().query(CalendarContract.Calendars.CONTENT_URI, projection, CalendarContract.Calendars.VISIBLE + " = 1", null, CalendarContract.Calendars._ID + " ASC"); 
} 
関連する問題