-2

I gave some tries to access the calendars on a Android phone, but none of my code worked, is there someone that knows for sure, how to read/query the calendar events for a specified time range?

Erdinc Ay
  • 3,224
  • 4
  • 27
  • 42

1 Answers1

11
String[] projection = new String[] { CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DESCRIPTION, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events.ALL_DAY, CalendarContract.Events.EVENT_LOCATION };

// 0 = January, 1 = February, ...

Calendar startTime = Calendar.getInstance();
startTime.set(2014,00,01,00,00);

Calendar endTime= Calendar.getInstance();
endTime.set(2015,00,01,00,00);

// the range is all data from 2014

String selection = "(( " + CalendarContract.Events.DTSTART + " >= " + startTime.getTimeInMillis() + " ) AND ( " + CalendarContract.Events.DTSTART + " <= " + endTime.getTimeInMillis() + " ))";

Cursor cursor = this.getBaseContext().getContentResolver().query( CalendarContract.Events.CONTENT_URI, projection, selection, null, null );

// output the events 

if (cursor.moveToFirst()) {
    do {
        Toast.makeText( this.getApplicationContext(), "Title: " + cursor.getString(1) + " Start-Time: " + (new Date(cursor.getLong(3))).toString(), Toast.LENGTH_LONG ).show();
    } while ( cursor.moveToNext());
}
Erdinc Ay
  • 3,224
  • 4
  • 27
  • 42
  • found the solution, this is by way the best answer ever made to this question – Erdinc Ay Nov 11 '14 at 09:07
  • 1
    Finally one solution! – Ton May 25 '16 at 09:13
  • cursor = this.getBaseContext().getContentResolver().query(CalendarContract.Events.CONTENT_URI, projection, selection, null, null); – akhil batlawala Jul 27 '16 at 06:27
  • 1
    Unable to start activity ComponentInfo{fourever.autogreetingapp/fourever.autogreetingapp.mainclasses.ListViewActivity}: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.calendar.CalendarProvider2 from ProcessRecord{5368732 14892:fourever.autogreetingapp/u0a181} (pid=14892, uid=10181) requires android.permission.READ_CALENDAR or android.permission.WRITE_CALENDAR Both permission is given. – akhil batlawala Jul 27 '16 at 06:30
  • @akhilbatlawala this code works not on all Android versions, there are at least two different ways to access Calender (events) data, the version I use is for all older Android versions up to Android 4 I think but works also on Android 5. Please have a look on your permissions again, maybe you need more permissions. I unfortunately dont have the application code anymore. – Erdinc Ay Jul 27 '16 at 08:53