Events are adding to calendar properly till api 22.
I have also implemented run- time permissions for Marshmallow , Calender permission is allowed in Phone setting for my application is clearly visible.
But still nothing is updating on phone calendar and also app giving no error or warning.
Below is my method to add event programatically on phone calendar.
private void addEventToCalender(Activity ourActivity, String title, String desc, String place, int status, long startDate, long endDte, boolean needReminder, boolean needMailService) {
try {
String eventUriString = "content://com.android.calendar/events";
ContentValues eventValues = new ContentValues();
eventValues.put("calendar_id", 1); // id, We need to choose from // our mobile for primary its 1
eventValues.put("title", "My Title");
eventValues.put("description","My Description" );
eventValues.put("eventLocation", "Noida,UP ";
eventValues.put("dtstart", startDate);
eventValues.put("dtend", endDte);
eventValues.put("allDay", 1); // 1 for whole day
//eventValues.put("rrule", "FREQ=YEARLY");
// values.put("allDay", 1); //If it is bithday alarm or such
// kind (which should remind me for whole day) 0 for false, 1
// for true
eventValues.put("eventStatus", 1); // This information is
// sufficient for most
// entries tentative (0),
// confirmed (1) or canceled
// (2):
eventValues.put("eventTimezone", "UTC/GMT " + Constants.tzone);
eventValues.put("hasAlarm", 1); // 0 for false, 1 for true
Uri eventUri = this.getApplicationContext().getContentResolver().insert(Uri.parse(eventUriString), eventValues);
long eventID = Long.parseLong(eventUri.getLastPathSegment());
Log.i("eventID", eventID + "");
showSnackBar("Event added to calender successfuly.");
} catch (Exception ex) {
Log.e("error", "Error in adding event on calendar" + ex.getMessage());
showSnackBar("Ünable to add event to calender!");
}
}
May be you want to use inside Fragment .
at first use :
super.requestPermissions( new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
Inside fragment, you need to call:
FragmentCompat.requestPermissions(permissionsList, RequestCode)
Note:
ActivityCompat.requestPermissions(Activity, permissionsList, RequestCode);
add this library for FragmentCompat class in app.gradle.
compile 'com.android.support:support-v13:version_of_library'
Related
I am following this gist, to insert event into Calendar
How do I update existing Calendar Event, which i have inserted earlier using below code:
public void addToCalender() throws ParseException {
......
ContentValues event = new ContentValues();
event.put(CalendarContract.Events.CALENDAR_ID, calendarId[0]);
event.put(CalendarContract.Events.TITLE, "Event Title");
event.put(CalendarContract.Events.DESCRIPTION, "Event Description");
event.put(CalendarContract.Events.EVENT_LOCATION, "Eevnt Location");
event.put(CalendarContract.Events.DTSTART, startCalTime);
event.put(CalendarContract.Events.DTEND, endCalTime);
event.put(CalendarContract.Events.STATUS, 1);
event.put(CalendarContract.Events.HAS_ALARM, 1);
event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
Uri insertEventUri = AddEventActivity.this.getContentResolver().insert(
eventsUri, event);
ContentValues reminders = new ContentValues();
reminders.put(Reminders.EVENT_ID,
Long.parseLong(insertEventUri.getLastPathSegment()));
reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
reminders.put(Reminders.MINUTES, 10);
AddEventActivity.this.getContentResolver().insert(remainderUri, reminders);
}
I would like to know, How do I :
1. Remove existing event
2. Update existing event
Here is how you can modify an event. Let's say its ID is eventID:
public void updateEvent(int eventID)
{
ContentResolver cr = context.getContentResolver();
Uri eventUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
ContentValues event = new ContentValues();
event.put(CalendarContract.Events.TITLE, "new title");
event.put(CalendarContract.Events.DESCRIPTION, "My cool event!");
cr.update(eventUri, event, null, null);
}
To remove an event, you have two possibilities:
If you are a standard application:
Use the previous code and replace all the event.put by this one:
event.put(CalendarContract.Events.DELETED, 1);
If you are the SyncAdapter of the calendar and want a real deletion (The previous method just says that the event should be deleted and the one that follows must be used once the calendar is being synced :
public deleteEvent(Uri eventUri)
{
cr.delete(event, null, null);
}
Where eventUri is the Uri of the event obtained as shown previously from the event ID.
For all of the previous methods, if you get an exception about not being in a sync adapter, you can use this:
public static Uri asSyncAdapter(Uri uri, String account, String accountType)
{
return uri.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, account)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, accountType)
.build();
}
I hope this will help you.
Source: personnal code + http://developer.android.com/guide/topics/providers/calendar-provider.html
...
Outlook in fact seems to respond to the rules defined in RFC 2446
In summary you have to specify
METHOD:REQUEST and ORGANIZER:xxxxxxxx
...
Please read the original answer by Tom Carter.
I need to open Android device's Calendar app with some pre-populated data. The logic that Iam using seems to populate fields like:
Event description
Event location
From Date, To Date
All day event/not
Repeat /Recurrence Info
I am not able to populate "Reminders" section, I would like to populate Reminders section. It will great to get some help on this
Here is the code that I am using to open Calendar app and populate date.
// Intent to open Calendar Event
Intent intent = new Intent(Intent.ACTION_INSERT)
.setData(Events.CONTENT_URI);
intent.putExtra(Events.DESCRIPTION, desc);
intent.putExtra(Events.EVENT_LOCATION, location);
intent.putExtra(Events.TITLE, summary);
intent.putExtra(Events.EVENT_TIMEZONE, beginTime.getTimeZone().getID());
intent.putExtra(Events.STATUS, statusStr);
intent.putExtra(Events.VISIBLE, transparency);
intent.putExtra(Events.RRULE, "FREQ=YEARLY;INTERVAL=1;BYYEARDAY=1,2;UNTIL=20161210;");
intent.putExtra(Events.EXDATE, androidExDateStr.toString());
// Not sure on how to use CalendarContract.Reminders, Tried the following but does not seem to be working
intent.putExtra(CalendarContract.Reminders.DESCRIPTION, desc);
intent.putExtra(CalendarContract.Reminders.EVENT_LOCATION, location);
intent.putExtra(CalendarContract.Reminders.TITLE, summary);
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis());
intent.putExtra(CalendarContract.Reminders.DTSTART, beginTime.getTimeInMillis());
intent.putExtra(CalendarContract.Reminders.EVENT_TIMEZONE, beginTime.getTimeZone().getID());
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis());
intent.putExtra(CalendarContract.Reminders.DTEND, endTime.getTimeInMillis());
intent.putExtra(CalendarContract.Reminders.STATUS, statusStr);
intent.putExtra(CalendarContract.Reminders.RRULE,"FREQ=YEARLY;INTERVAL=1;BYYEARDAY=1,2;UNTIL=20161210;");
intent.putExtra(CalendarContract.Reminders.EXDATE, androidExDateStr.toString());
//intent.putExtra(CalendarContract.Reminders.METHOD, Reminders.METHOD_EMAIL);
//intent.putExtra(CalendarContract.Reminders.MINUTES, reminderVal) ;
//intent.putExtra(CalendarContract.Events.HAS_ALARM, 1);
//}
try {
context.startActivity(intent);
} catch(Exception e) {
e.printStackTrace();
Log.v(LOG_TAG, "Cannot schedule Calendar event as specified ");
return false;
}
Did you check the example from http://developer.android.com/guide/topics/providers/calendar-provider.html#reminders?
long eventID = 221;
...
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(Reminders.MINUTES, 15);
values.put(Reminders.EVENT_ID, eventID);
values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
Uri uri = cr.insert(Reminders.CONTENT_URI, values);
I'm trying to add event through an calendar intent. However, I can't figure out how to get the event ID of the event just added.
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", sdate.getTime());
intent.putExtra("endTime", edate.getTime());
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("title", "A Test Event from android app");
intent.putExtra("description", "Description here");
intent.putExtra("eventLocation", "location here here here");
I read extensively on other resources and can't seem to find an answer. I tried startActivityForResult but I can't seem to get it work. Other methods I try can't seem to check for it until the activity ends.
Is there any other way to get the event ID after the event has been added to the calendar? I need to use the intent method for this.
Try this one solution:
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
public class CalenderUtils {
/**
* Add a new event into a native Google calendar. Add alert notification by setting <code>isRemind</code> as <code>true</code>.
* #param cr - ContentResolver
* #param title - Event title
* #param addInfo - Event description
* #param place - Event place
* #param status - <code>int</code> This information is sufficient for most entries: tentative (0), confirmed (1) or canceled (2):
* #param startDate - <code>long</code> event start time in mls
* #param isRemind - <code>boolean</code> need to remind about event before?
* #param isMailService - <code>boolean</code>. Adding attendees to the meeting
* #return <code>long</code> eventID
*/
public static long addEventToCalender(ContentResolver cr, String title, String addInfo, String place, int status,
long startDate, boolean isRemind, boolean isMailService) {
String eventUriStr = "content://com.android.calendar/events";
ContentValues event = new ContentValues();
// id, We need to choose from our mobile for primary its 1
event.put("calendar_id", 1);
event.put("title", title);
event.put("description", addInfo);
event.put("eventLocation", place);
event.put("eventTimezone", "UTC/GMT +2:00");
// For next 1hr
long endDate = startDate + 1000 * 60 * 60;
event.put("dtstart", startDate);
event.put("dtend", endDate);
//If it is bithday alarm or such kind (which should remind me for whole day) 0 for false, 1 for true
// values.put("allDay", 1);
event.put("eventStatus", status);
event.put("hasAlarm", 1);
Uri eventUri = cr.insert(Uri.parse(eventUriStr), event);
long eventID = Long.parseLong(eventUri.getLastPathSegment());
if (isRemind) {
String reminderUriString = "content://com.android.calendar/reminders";
ContentValues reminderValues = new ContentValues();
reminderValues.put("event_id", eventID);
// Default value of the system. Minutes is a integer
reminderValues.put("minutes", 5);
// Alert Methods: Default(0), Alert(1), Email(2), SMS(3)
reminderValues.put("method", 1);
cr.insert(Uri.parse(reminderUriString), reminderValues); //Uri reminderUri =
}
if (isMailService) {
String attendeuesesUriString = "content://com.android.calendar/attendees";
/********* To add multiple attendees need to insert ContentValues multiple times ***********/
ContentValues attendeesValues = new ContentValues();
attendeesValues.put("event_id", eventID);
// Attendees name
attendeesValues.put("attendeeName", "xxxxx");
// Attendee email
attendeesValues.put("attendeeEmail", "yyyy#gmail.com");
// Relationship_Attendee(1), Relationship_None(0), Organizer(2), Performer(3), Speaker(4)
attendeesValues.put("attendeeRelationship", 0);
// None(0), Optional(1), Required(2), Resource(3)
attendeesValues.put("attendeeType", 0);
// None(0), Accepted(1), Decline(2), Invited(3), Tentative(4)
attendeesValues.put("attendeeStatus", 0);
cr.insert(Uri.parse(attendeuesesUriString), attendeesValues); //Uri attendeuesesUri =
}
return eventID;
}
}
i copypasted this class from my project so you are welcome to change names as you prefer.
As you notice here u receive id value after insertion.
If you need get reminderId or meeting id with attendees - you have to handle a return value from cr.insert... and then parce uri long id = Long.parseLong(uri.getLastPathSegment());
Here is an additional info: CalendarContract.Events and Calendar chapter
As part of a project, I created an android application which communicates with an online database (MySQL) to integrate the appointment has taken the online calendar.
I collect the data, converted to Json, but when the inscrires in the agenda of android mobile I encounter a probleme, here is my code : (sorry for my english )
EDIT :
public class calendrier extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor cursor = getContentResolver()
.query(Uri.parse("content://com.android.calendar/calendars"),
new String[] { "_id", "displayName" }, "selected=1",
null, null);
if (cursor != null && cursor.moveToFirst()) {
String[] calNames = new String[cursor.getCount()];
int[] 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();
}
cursor.close();
if (calIds.length > 0) {
// we're safe here to do any further work
}
// grab calendar id from above
int cal_id = calIds[0];
// set the content value
ContentValues cv = new ContentValues();
cv.put("calendar_id", cal_id);
cv.put("title", "titre");
cv.put("description", "bla bla bla");
cv.put("eventLocation", "city");
// note: you're going to need to convert the desired date into
// milliseconds
cv.put("dtstart", System.currentTimeMillis());
cv.put("dtend", System.currentTimeMillis()
+ DateUtils.DAY_IN_MILLIS);
cv.put("allDay", 0); // true = 1, false = 0
cv.put("hasAlarm", 1);
// once desired fields are set, insert it into the table
getContentResolver().insert(
Uri.parse("content://com.android.calendar/events"), cv);
}
}
}
this code works but it asks me if I want to participate in the event when I open it and I wish he does not do
thanks
//did U include permission in your manifest.xml file
android.permission.READ_CALENDAR
android.permission.WRITE_CALENDAR
String WRITE_CALENDAR Allows an application to write (but not read) the user's calendar data.
The Uri of Calendar has changed from Android 2.2 .
Old (2.1 and before): content://calendar/
New (2.2): content://com.android.calendar/
Change your Uri to the new one.
There is no Calendar Application by default in Android. So the Uri may not work at all.
If, you are getting the first error message as "Failed to find provider info for com.android.calendar", you need to check the handset you are using to debug uses which Calendar URI.
To insert Time in Calendar event, you can use the following code example:
Calendar calendar = Calendar.getInstance();
calendar.getTimeInMillis();
cv.put("dtstart", ""+calendar.getTimeInMillis());
cv.put("dtend", ""+calendar.getTimeInMillis()+10000);
I have added a calendar event programatically using the caledarcontract api and obtained a eventId. Similarly i added a reminder for this event and saved the reminderId too. Now i dont want a reminder for this event(or i would like to turn off the reminder), so i am trying to delete the reminder using the reminderId but i am not able to delete. I tried to delete the reminder using the eventId too but its not working.
public int AddEventToCalendar(String calendarId, Entity entity) {
// TODO Auto-generated method stub
ContentValues event = new ContentValues();
event.put("calendar_id", calendarId);
event.put("title", entity.description);
event.put("dtstart", System.currentTimeMillis());
event.put("dtend", System.currentTimeMillis() + 3600*1000);
event.put("allDay", 0);
//status: 0~ tentative; 1~ confirmed; 2~ canceled
event.put("eventStatus", 1);
//0~ default; 1~ confidential; 2~ private; 3~ public
event.put("visibility", 0);
//0~ opaque, no timing conflict is allowed; 1~ transparency, allow overlap of scheduling
event.put("transparency", 0);
//0~ false; 1~ true
event.put("hasAlarm", 1);
Uri add_eventUri;
if (Build.VERSION.SDK_INT >= 8) {
add_eventUri = Uri.parse("content://com.android.calendar/events");
} else {
add_eventUri = Uri.parse("content://calendar/events");
}
Uri l_uri = context.getContentResolver().insert(add_eventUri, event);
if(l_uri != null)
{
long eventID = Long.parseLong(l_uri.getLastPathSegment());
return (int) eventID;
}
else
return 0;
}
public int AddReminderOnEvent(Entity entity)
{
if(entity.eventId != 0)
{
ContentValues reminderValues = new ContentValues();
reminderValues.put("event_id", entity.eventId);
reminderValues.put("method", 1);// will alert the user with a reminder notification
reminderValues.put("minutes", 0);// number of minutes before the start time of the event to fire a reminder
Uri reminder_eventUri;
if (Build.VERSION.SDK_INT >= 8) {
reminder_eventUri = Uri.parse("content://com.android.calendar/reminders");
} else {
reminder_eventUri = Uri.parse("content://calendar/reminders");
}
Uri r_uri = context.getContentResolver().insert(reminder_eventUri, reminderValues);
if(r_uri != null)
{
long reminderID = Long.parseLong(r_uri.getLastPathSegment());
return (int) reminderID;
// Toast.makeText(getApplicationContext(), "Event Created Successfully", Toast.LENGTH_LONG).show();
}
else
return 0;
}
else
{
return 0;
}
}
public boolean DeleteReminderOnTask(int eventId, int reminderId) {
// TODO Auto-generated method stub
Uri delete_reminderUri;
if (Build.VERSION.SDK_INT >= 8) {
delete_reminderUri = Uri.parse("content://com.android.calendar/reminders");
} else {
delete_reminderUri = Uri.parse("content://calendar/reminders");
}
delete_reminderUri = ContentUris.withAppendedId(delete_reminderUri, reminderId);
int rows = context.getContentResolver().delete(delete_reminderUri,null , null);
if(rows > 0)
return true;
else
return false;
}
After executing this code everytime the rows returns 0 meaning that no rows have been altered. And the reminder comes up exactly at the appropriate time. How to delete the reminder from the calendar without deleting the event?
I'm not sure which SDK version you're running against when failing, but this code (which is essentially the same as yours, less the version check) works for me:
Uri reminderUri = ContentUris.withAppendedId(
CalendarContract.Reminders.CONTENT_URI, reminderId);
int rows = contentResolver.delete(reminderUri, null, null);
I got reminderId by querying the event's reminders:
String[] projection = new String[] {
CalendarContract.Reminders._ID,
CalendarContract.Reminders.METHOD,
CalendarContract.Reminders.MINUTES
};
Cursor cursor = CalendarContract.Reminders.query(
contentResolver, eventId, projection);
while (cursor.moveToNext()) {
long reminderId = cursor.getLong(0);
int method = cursor.getInt(1);
int minutes = cursor.getInt(2);
// etc.
}
cursor.close();
This might not be the only or best way, but all I could figure out was how to remove all reminders for an event. I don't know of a way to remove just one reminder.
//What we want to update
ContentValues values = new ContentValues();
values.put(Events.HAS_ALARM, 0);
//We're setting the event to have no alarms
int result = getContentResolver().update(
Events.CONTENT_URI,
values,
Events._ID + " = ?",
new String[]{"44"}
);
Unfortunately, this removes all reminders, but I'm not sure multiple reminders are really supported by Android 14+ or most calendar providers (e.g. Exchange). The calendar app in ICS only allows adding one reminder (despite saying "Add Reminders").
And if i use another application such as Business Calendar to add multiple reminders, when I check in Exchange, it only shows ones reminder. It does show multiple reminders in the calendar app but only on that device, not on other devices, so multiple reminders seem to be local only.