Below is my code to Add calendar Account and then adding Event to that calendar,
AuthenticationManager.getInstance().setContextActivity(this);
AuthenticationManager.getInstance().connect(
new AuthenticationCallback<AuthenticationResult>() {
#Override
public void onSuccess(AuthenticationResult result) {
Log.i(TAG, "onConnectButtonClick - Successfully connected to Office 365");
String type = result.getUserInfo().getIdentityProvider();
String accountOwner = result.getUserInfo().getDisplayableId();
addCalendar(type, accountOwner);
}
#Override
public void onError(final Exception e) {
Log.e(TAG, "onCreate - " + e.getMessage());
}
});
Calendar Method:
public void addCalendar(String type, String accountOwner) {
ContentValues contentValues = new ContentValues();
contentValues.put(CalendarContract.Calendars.ACCOUNT_NAME, accountOwner);
contentValues.put(CalendarContract.Calendars.ACCOUNT_TYPE, type);
contentValues.put(CalendarContract.Calendars.NAME, accountOwner);
contentValues.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, "Outlook");
contentValues.put(CalendarContract.Calendars.CALENDAR_COLOR, "232323");
contentValues.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_EDITOR);
contentValues.put(CalendarContract.Calendars.OWNER_ACCOUNT, accountOwner);
contentValues.put(CalendarContract.Calendars.ALLOWED_REMINDERS, "METHOD_ALERT, METHOD_EMAIL, METHOD_ALARM");
contentValues.put(CalendarContract.Calendars.ALLOWED_ATTENDEE_TYPES, "TYPE_OPTIONAL, TYPE_REQUIRED, TYPE_RESOURCE");
contentValues.put(CalendarContract.Calendars.ALLOWED_AVAILABILITY, "AVAILABILITY_BUSY, AVAILABILITY_FREE, AVAILABILITY_TENTATIVE");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, 23);
}
Uri uri = CalendarContract.Calendars.CONTENT_URI;
uri = uri.buildUpon().appendQueryParameter(android.provider.CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountOwner)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, type).build();
getContentResolver().insert(uri, contentValues);
}
Adding Event:
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, beginTime.getTimeInMillis());
values.put(CalendarContract.Events.DTEND, endTime.getTimeInMillis());
values.put(CalendarContract.Events.TITLE, "Tech Stores");
values.put(CalendarContract.Events.DESCRIPTION, "Successful Startups");
values.put(CalendarContract.Events.CALENDAR_ID, 10);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
values.put(CalendarContract.Events.EVENT_LOCATION, "London");
values.put(CalendarContract.Events.GUESTS_CAN_INVITE_OTHERS, "1");
values.put(CalendarContract.Events.GUESTS_CAN_SEE_GUESTS, "1");
values.put(CalendarContract.Events.ORGANIZER, "azhar#outlook.com");
cr.insert(CalendarContract.Events.CONTENT_URI, values);
The problem is, the event is not getting added to the desired Calendar. I'm not getting any error too. Any correction needed here?
You could add “ CALENDAR_ID ” parameter to the Events, For example:
values.put(CalendarContract.Events. CALENDAR_ID, “”);
For more information, please refer to this link:
CalendarContract.Events
Related
#SuppressLint({"RxLeakedSubscription", "RxSubscribeOnError"})
public static long pushAppointmentsToCalender(Activity curActivity, String title, String addInfo, String place, int status, long startDate, boolean needReminder) {
/***************** Event: note(without alert) *******************/
ContentResolver cr = curActivity.getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, startDate);
values.put(CalendarContract.Events.DTEND, startDate);
values.put(CalendarContract.Events.TITLE, title);
values.put(CalendarContract.Events.DESCRIPTION, addInfo);
values.put(CalendarContract.Events.CALENDAR_ID, startDate);
values.put(CalendarContract.Events.EVENT_TIMEZONE, "Asia/Calcutta");
#SuppressLint("MissingPermission") Uri uriEvent = cr.insert(CalendarContract.Events.CONTENT_URI, values);
long eventID = Long.parseLong(uriEvent.getLastPathSegment());
try {
if (needReminder) {
ContentResolver crreminder = curActivity.getContentResolver();
ContentValues valuesreminder = new ContentValues();
valuesreminder.put(CalendarContract.Reminders.EVENT_ID, eventID);
valuesreminder.put(CalendarContract.Reminders.MINUTES, 15);
valuesreminder.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
#SuppressLint("MissingPermission") Uri uri = crreminder.insert(CalendarContract.Reminders.CONTENT_URI, valuesreminder);
}
}catch (Exception e){
e.printStackTrace();
}
return eventID;
}
The error i am getting in logs is
2019-03-06 16:29:16.935 23021-23021/com.medikoe.connect.debug W/System.err: android.database.sqlite.SQLiteException
2019-03-06 16:29:16.936 23021-23021/com.medikoe.connect.debug
Event id is created successfully but while inserting uri for reminder is creating sqlite exception . Please help!
Update: I found that this error can be occurred with in two conditions.
If you didn't config your google calendar app in your
phone/emulator this error will occur. Then make sure that you configure the google calendar app with a gmail account before running the app.
If you are passing wrong formatted or false time to the event or reminder. use unix time with correct time zone.
Recently, I also faced same issue. Finally, I found the solution.
First of all, you have to find all logged in gmail id from the device and then select any one gmail account and find its calendar id. After that you have to pass that id to the event query like this....
values.put(Events.CALENDAR_ID, calendarId);
at last call you function
See below method for finding email id's...
public static Hashtable listCalendarId(Context context) {
try {
if (haveCalendarReadWritePermissions((Activity) context)) {
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()) {
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String, String> calendarIdTable = new Hashtable<>();
do {
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName, calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I'm using below code in Marshmellow device to add the event to the Calendar programmatically but it's not working. Any idea? I cannot see this event in the Calendar app.
long startMillis = 0;
long endMillis = 0;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = null, endDate = null;
try{
startDate = simpleDateFormat.parse("2017-05-01 01:30:00");
startMillis = startDate.getTime();
endDate = simpleDateFormat.parse("2017-05-01 03:30:00");
endMillis = endDate.getTime();
}catch (ParseException e){
e.printStackTrace();
}
ContentResolver cr = this.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, "Hello Title");
values.put(CalendarContract.Events.DESCRIPTION, "Add events to Calendar");
values.put(CalendarContract.Events.CALENDAR_ID, 879);
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
PS: It works if only one gmail account is synced with the calendar app.
Am also find so many solutions finally i got solution and successfully calendar event added with Schedule event.
Step -1 > Enable Google calnedar API From google console.
Step - 2 > Add the permission in Androidmanifest.xml
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
Step =3 > Add library for checking Permissions in your .gradle
compile 'com.karumi:dexter:4.1.0'
Dexter.withActivity(YoutActivityName.this)
.withPermission(Manifest.permission.WRITE_CALENDAR)
.withListener(new PermissionListener()
{
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
try {
int calenderId = -1;
String calenderEmaillAddress = "sathishmicit2012#gmail.com";
String[] projection = new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.ACCOUNT_NAME};
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection,
CalendarContract.Calendars.ACCOUNT_NAME + "=? and (" +
CalendarContract.Calendars.NAME + "=? or " +
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + "=?)",
new String[]{calenderEmaillAddress, calenderEmaillAddress,
calenderEmaillAddress}, null);
if (cursor.moveToFirst()) {
if (cursor.getString(1).equals(calenderEmaillAddress)) {
calenderId = cursor.getInt(0);
}
}
long start2 = Calendar.getInstance().getTimeInMillis(); // 2011-02-12 12h00
long end2 = Calendar.getInstance().getTimeInMillis() + (4 * 60 * 60 * 1000); // 2011-02-12 13h00
String title = "This is my demo test with alaram with 5 minutes";
ContentValues cvEvent = new ContentValues();
cvEvent.put("calendar_id", calenderId);
cvEvent.put(CalendarContract.Events.TITLE, title);
cvEvent.put(CalendarContract.Events.DESCRIPTION, String.valueOf(start2));
cvEvent.put(CalendarContract.Events.EVENT_LOCATION, "Bhatar,Surat");
cvEvent.put("dtstart", start2);
cvEvent.put("hasAlarm", 1);
cvEvent.put("dtend", end2);
cvEvent.put("eventTimezone", TimeZone.getDefault().getID());
Uri uri = getContentResolver().insert(Uri.parse("content://com.android.calendar/events"), cvEvent);
// get the event ID that is the last element in the Uri
long eventID = Long.parseLong(uri.getLastPathSegment());
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, 2);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALARM);
cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
//Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {/* ... */}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
}).check();
Hello Calender ID is 879 you cant take it random. Calender ID must be from this URI content://com.android.calendar/calendars
int calenderId=-1;
String calenderEmaillAddress="xxx#gmail.com";
String[] projection = new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.ACCOUNT_NAME};
ContentResolver cr = activity.getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection,
CalendarContract.Calendars.ACCOUNT_NAME + "=? and (" +
CalendarContract.Calendars.NAME + "=? or " +
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + "=?)",
new String[]{calenderEmaillAddress, calenderEmaillAddress,
calenderEmaillAddress}, null);
if (cursor.moveToFirst()) {
if (cursor.getString(1).equals(calenderEmaillAddress))
calenderId=cursor.getInt(0); //youre calender id to be insered in above your code
}
I've build an app which allows to synchronize the app specific data with the google calendar.
To add my events to the calendar I've got the following method, which works fine.
private static void addCalendarEvents(Context context, Cursor c) {
if (c.moveToFirst()) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
while (!c.isAfterLast() && !c.isBeforeFirst()) {
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, start);
values.put(CalendarContract.Events.DTEND, end);
values.put(CalendarContract.Events.TITLE, title);
values.put(CalendarContract.Events.DESCRIPTION, description);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.HAS_ALARM, false);
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
c.moveToNext();
}
}
}
}
The added events are visible in the google calendar app. My problem is, that I also want to be able to delete (and update) MY EVENTS from the calendar again.
How can I achieve that? I only found solutions to remove all events from the calendar.
Do I have to create an own calendar? How can I automatically let this calendar be synced with the google calendar? Or do I have to save all event ids I added?
I decided to save the calendarEventIds as a additional column in my database as follows which works as a charm:
private static void addCalendarEvents(Context context, Cursor c) {
if (c.moveToFirst()) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
while (!c.isAfterLast() && !c.isBeforeFirst()) {
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, start);
values.put(CalendarContract.Events.DTEND, end);
values.put(CalendarContract.Events.TITLE, title);
values.put(CalendarContract.Events.DESCRIPTION, description);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.HAS_ALARM, false);
long eventID;
// The row has an event id, so the event should be updated not created
if ((eventID = c.getLong(c.getColumnIndex(LessonDatabaseManagement.KEY_CALENDAR_EVENT_ID))) != -1) {
Uri eventUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
cr.update(eventUri, values, null, null);
} else {
// The row hasn't an event id, so the event should be created
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
eventID = Long.parseLong(uri.getLastPathSegment());
new LessonDatabaseManagement(this)
.updateCalendarEventId(c.getInt(c.getColumnIndex(LessonDatabaseManagement.KEY_ID)), eventID);
}
c.moveToNext();
}
}
}
}
To delete:
private void removeCalendarEvents() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
Cursor c = new LessonDatabaseManagement(this).getAllCalendarEventIds();
if (c.moveToFirst()) {
while (!c.isAfterLast() && !c.isBeforeFirst()) {
long eventID;
if ((eventID = c.getLong(c.getColumnIndex(LessonDatabaseManagement.KEY_CALENDAR_EVENT_ID))) != -1) {
Uri eventUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
this.getContentResolver().delete(eventUri, null, null);
}
c.moveToNext();
}
}
new LessonDatabaseManagement(this).removeAllCalendarEventIds();
}
}
I'm trying to insert event using this method, it is getting executed properly but no contact event is in the contact.
private static void addEvent(ArrayList<ContentProviderOperation> contact_list,
ContactDataBean contactBean, int rawContactID){
contact_list.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID,
rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.TYPE_OTHER)
.withValue(ContactsContract.CommonDataKinds.Event.START_DATE,
contactBean.value).build());
try {
// Executing all the insert operations as a single
// database
// transaction
context.getContentResolver().applyBatch(
ContactsContract.AUTHORITY, contact_list);
Toast.makeText(context, "Contact is successfully added",
Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
No Error and no event is getting inserted.What's the problem??
you should add account(using calendar) or using intent
using intent:
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("title", "Event with " + cname);
intent.putExtra("beginTime", System.currentTimeMillis());
intent.putExtra("endTime", System.currentTimeMillis() + 1800 * 1000);
intent.putExtra("allDay", 0);
intent.putExtra("hasAlarm", 1);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, 103);
or using calander
TimeZone tz = TimeZone.getDefault();
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, startMillis);
values.put(CalendarContract.Events.DTEND, endMillis);
values.put(CalendarContract.Events.TITLE, "Reminder - " + cname);
values.put(CalendarContract.Events.DESCRIPTION, note);
values.put(CalendarContract.Events.CALENDAR_ID, calID);
values.put(CalendarContract.Events.EVENT_TIMEZONE, tz.getDisplayName());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
long eventID = Long.parseLong(uri.getLastPathSegment());
values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, 5);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
I am trying to add events to a user's calendar programatically. I have followed countless guides here on StackOverflow and elsewhere, but none of them will make that damned event show up in my calendar. Here is my current code:
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());
}
}
Basically what is going on is that the user presses an action bar button, which calls the saveGamesToCalendar() method, which calls the ShowCalendarPopup() method. This method shows a standard dialog with the list of the user's calendars, and when the user selects one of them, the loopThroughGames() method is called with the ID of the chosen calendar as a parameter. This method will, when everything is working, write all the user's games to the calendar, but for testing purposes it only writes one. The addGameToCalendar() method takes a game object, which holds lots of values like time, title, location, date, etc., and inserts it into the calendar using the standard way outlined in many different places on the web.
I am getting no error messages with this code (other than the ones I send to the error log myself) so I have no idea why this code isn't working. No errors, just the games never show up in my calendar. I have the permissions set correctly in the manifest so I know that isn't the problem.
Does anyone have a solution to this annoying problem? Thanks for your help!
[RE-EDIT]]
This is what I did and it works like a charm..
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();
}
protected 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);
}
This works and is much easier to understand:
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);