14

We are trying to show user the Ice cream Sandwich calendar view, when they want to add a new event. We can only test this in emulator.

The other problem is that we can't find any examples how to use CalendarProvider. This is the right class when it comes to dealing with Sandwich calendar?

Would this be easier to do with Google Gdata API?

[EDIT] So what we got working was adding an event to calendar but it was not through the API, we open the calendar in the correct view. But now the problem is that it does not work in the emulator because we haven't been able to get the calendar synced.

So the question is: How to read and possibly edit Android calendar events using the new Android 4.0 Ice Cream Sandwich API?

1
  • don't forget about this line <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    – Sirop4ik
    Nov 8, 2018 at 8:34

6 Answers 6

53

Here's code that will let you add an event directly:

import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.CalendarContract;

import java.util.Calendar;

// Construct event details
long startMillis = 0;
long endMillis = 0;
Calendar beginTime = Calendar.getInstance();
beginTime.set(2012, 9, 14, 7, 30);
startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(2012, 9, 14, 8, 45);
endMillis = endTime.getTimeInMillis();

// Insert Event
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.DTSTART, startMillis);
values.put(CalendarContract.Events.DTEND, endMillis);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.TITLE, "Walk The Dog");
values.put(CalendarContract.Events.DESCRIPTION, "My dog is bored, so we're going on a really long walk!");
values.put(CalendarContract.Events.CALENDAR_ID, 3);
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);

// Retrieve ID for new event
String eventID = uri.getLastPathSegment();

You'll need the CALENDAR_ID, so here's how to query the list of calendars:

Uri uri = CalendarContract.Calendars.CONTENT_URI;
String[] projection = new String[] {
       CalendarContract.Calendars._ID,
       CalendarContract.Calendars.ACCOUNT_NAME,
       CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
       CalendarContract.Calendars.NAME,
       CalendarContract.Calendars.CALENDAR_COLOR
};

Cursor calendarCursor = managedQuery(uri, projection, null, null, null);

You'll need to request the android.permission.READ_CALENDAR permission for all of this to work.

If you want to avoid having to request permissions, you can also ask the Calendar app to create a new event on your behalf by using an Intent:

Intent intent = new Intent(Intent.ACTION_INSERT)
         .setType("vnd.android.cursor.item/event")
         .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
         .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
         .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY , false) // just included for completeness
         .putExtra(Events.TITLE, "My Awesome Event")
         .putExtra(Events.DESCRIPTION, "Heading out with friends to do something awesome.")
         .putExtra(Events.EVENT_LOCATION, "Earth")
         .putExtra(Events.RRULE, "FREQ=DAILY;COUNT=10") 
         .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
         .putExtra(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE)
         .putExtra(Intent.EXTRA_EMAIL, "my.friend@example.com");
startActivity(intent);
8
  • Will this code work if i have created my app using api level 8
    – AndroidDev
    Mar 5, 2012 at 5:55
  • @Anshuman: No. The public calendar API is new for API level 14.
    – Sparky
    Apr 11, 2012 at 9:22
  • 5
    As @Durai states, EVENT_TIMEZONE must also be added to ContentValues Jul 13, 2012 at 22:11
  • this does not work for me, is it because i have two calendars in android? android stock and splanner by samsung? How can you choose one dynamically?
    – jantox
    Apr 24, 2013 at 5:34
  • 1
    @jantox replace the line values.put(CalendarContract.Events.CALENDAR_ID, 3); with a value other than 3 as the second parameter. that needs to be a real calendar ID that exists on your phone. once you get the cursor, you can read it by doing Integer.parseInt(cursor.getString(cursor.getColumnIndex(CalendarContract.Calendars._ID)));. if you don't get it, just ask it as a question on stack overflow so i can give more details. and @reply me
    – David T.
    Aug 14, 2013 at 2:15
10

You can use the following code to setup the timezone and it works for me

TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
1
  • 1
    This is required to make the answer code work. The timezone is required.
    – Phobos
    May 7, 2012 at 3:31
2

Make sure,you are not using 'visibilty' for ICS and JellyBean devices (apiLevel>=14)

Try this -

ContentValues values= new ContentValues();
int apiLevel = android.os.Build.VERSION.SDK_INT;
            if(apiLevel<14)
            values.put("visibility", 0);

Use visibility only if device version is less than 14(ICS)

0

I have creted following Method to handle the flexibility of TIMEZONE

// Converting TimeZone in to GMT to save upon local Db to avoid // Controversy Over Server

private String convertDateTimeZone(long originalDate) {
        String newDate = "";
        Date date = new Date(originalDate);
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
        Date parsed = null;
        try {
            parsed = formatter.parse(formatter.format(date).toString());
            TimeZone tz = TimeZone.getTimeZone("GMT");
            SimpleDateFormat destFormat = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            destFormat.setTimeZone(tz);

            newDate = destFormat.format(parsed);
        } catch (Exception e) {
        }
        return newDate;
    }
0

I used the following code to read all the events in Calendar.

public boolean isEventInCal(Context context, String cal_meeting_id) {

    Cursor cursor = context.getContentResolver().query(
    Uri.parse("content://com.android.calendar/events"),
            new String[] { "_id" }, " _id = ? ",
            new String[] { cal_meeting_id }, null);

    if (cursor.moveToFirst()) {
        // will give all events
        return true;
    }

    return false;
}
0
public static ArrayList<String> readCalendarEvent(Context context) {
        Cursor cursor = context.getContentResolver()
                .query(
                        Uri.parse("content://com.android.calendar/events"),
                        new String[] { "calendar_id", "title", "description",
                                "dtstart", "dtend", "eventLocation" }, null,
                        null, null);
        cursor.moveToFirst();
        // fetching calendars name
        String CNames[] = new String[cursor.getCount()];

        // fetching calendars id
        nameOfEvent.clear();
        startDates.clear();
        endDates.clear();
        descriptions.clear();
        Log.d("cnameslength",""+CNames.length);
        if (CNames.length==0)
        {
         Toast.makeText(context,"No event exists in calendar",Toast.LENGTH_LONG).show();
        }
        for (int i = 0; i < CNames.length; i++) {

            nameOfEvent.add(cursor.getString(1));
            startDates.add(getDate(Long.parseLong(cursor.getString(3))));
            endDates.add(getDate(Long.parseLong(cursor.getString(4))));
            descriptions.add(cursor.getString(2));
            CNames[i] = cursor.getString(1);
            cursor.moveToNext();
            Log.d("datacur",""+nameOfEvent.get(i));
            Log.d("datacur",""+startDates.get(i));
            Log.d("datacur",""+endDates.get(i));
            Log.d("datacur",""+descriptions.get(i));
            String filename=nameOfEvent.get(i)+"::"+startDates.get(i)+"::"+endDates.get(i)+"::"+descriptions.get(i);
            generateNoteOnSD(context,nameOfEvent.get(i),filename);

        }
        return nameOfEvent;
    }





public static void generateNoteOnSD(Context context, String sFileName, String sBody) {
        try {
            File root = new File(Environment.getExternalStorageDirectory(), "Notes");
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, sFileName);
            FileWriter writer = new FileWriter(gpxfile);
            writer.append(sBody);
            writer.flush();
            writer.close();
            Toast.makeText(context, "Successfully Backup Created", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.