I want to insert a calendar event via intent. But the "add event"-Activity should not be prefilled with a reminder/alarm.
Intent intent = new Intent(Intent.ACTION_INSERT)
.setData(Events.CONTENT_URI)
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
.putExtra(Events.TITLE, title)
.putExtra(Events.DESCRIPTION, description)
.putExtra(Events.HAS_ALARM, false)
.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
This intent will start the calendar's "add event"-activity prefilled with some data. However, although I set Events.HAS_ALARM to false, the activity is pre-populated with a reminder (tested on Android ICS).
What's even worse, the reminder is prepopulated to 10 minutes before the event, which in case of an all-day event is really bad. Who wants to be reminded at 11.50 pm of an event the next day?
What I am missing here?
I never tried your technique above. Here is the code snippet I use to save Calendar.
public static void saveCalendar(Context ctx, String title,
String description, String location, Calendar cal_start,
Calendar cal_end) {
// look for calendar
Cursor cursor = ctx.getContentResolver()
.query(Uri.parse("content://com.android.calendar/calendars"),
new String[] { "_id", "displayname" }, "selected=1",
null, 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();
// put calendar event
ContentValues event = new ContentValues();
event.put("calendar_id", CalIds[0]);
event.put("title", title);
event.put("description", description);
event.put("eventLocation", location);
event.put("dtstart", cal_start.getTimeInMillis());
event.put("dtend", cal_end.getTimeInMillis());
event.put("hasAlarm", 1);
Uri eventsUri = Uri.parse("content://com.android.calendar/events");
Uri newEvent = ctx.getContentResolver().insert(eventsUri, event);
// put alarm reminder for an event, 2 hours prior
long eventID = Long.parseLong(newEvent.getLastPathSegment());
ContentValues cv_alarm = new ContentValues();
cv_alarm.put("event_id", eventID);
cv_alarm.put("method", 1);
cv_alarm.put("minutes", 120);
ctx.getContentResolver()
.insert(Uri.parse("content://com.android.calendar/reminders"),
cv_alarm);
}
It you don't want the alarm/reminder set 0 to hasAlarm and don't put the codes to add the alarm. It works for me.
The column HAS_ALARM expects an Integer boolean of 0 or 1.
intent.putExtra(Events.HAS_ALARM, 0);
Related
I'd like to add an event and get it back programmatically in android. I have two option to add an event to the calender but neither of them good at adding ID to the event. I set the number of the ID into 32 but when I create an event it's ID is growing up. Then how can I add the ID I want?
Option1:
public void InsertAnEvent2(){
Calendar calendarEvent = Calendar.getInstance();
Intent i = new Intent(Intent.ACTION_EDIT);
i.setType("vnd.android.cursor.item/event");
i.putExtra("beginTime", calendarEvent.getTimeInMillis());
i.putExtra("allDay", true);
i.putExtra("rule", "FREQ=YEARLY");
i.putExtra("endTime", calendarEvent.getTimeInMillis() + 60 * 60 * 1000);
i.putExtra("title", "Eskuvo");
i.putExtra("calendar_id",32);
startActivity(i);
}
Option2:
public void Mindencalendar(){
ContentResolver cr = getActivity().getContentResolver();
Calendar calendarEvent = Calendar.getInstance();
Log.d("i'm","here1");
long idk[] = new long[10];
idk[0] = cu.addEventToCalender(cr,"a","b","c",5,calendarEvent.getTimeInMillis());
Log.d("id","id"+idk[0]);
}
public class CalendarUtils {
public static long addEventToCalender(ContentResolver cr, String title, String addInfo, String place, int status,
long startDate) {
String eventUriStr = "content://com.android.calendar/events";
ContentValues event = new ContentValues();
event.put("calendar_id", 32);
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());
return eventID;
}
}
But maybe the problem is how I try to read these events. Here is my code:
public void ReadFromCalendar(){
Uri EVENTS_URI = Uri.parse("content://com.android.calendar/" + "events");
ContentResolver cr = getActivity().getContentResolver();
Cursor cursor;
cursor = cr.query(EVENTS_URI, null, null, null, null);
//int a = cursor.getCount();
while(cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndex("calendar_id"));
Log.d("TAG", "ID: " + id);
Uri eventUri = ContentUris.withAppendedId(EVENTS_URI, id);
}
cursor.close();
}
I don't know where do I make a mistake. If anyone has an idea please response.
Can you post the database structure, one of the first thoughts was that your calendar_id column has the auto-increment enabled. In that case you can add another column to your table or alter the existing one, my recommendation is to add another one. But let's see the columns table details.
I am using below code to add events to calendar on android
public void addEvent(String datetime) {
String eventdate;
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");
final Calendar cal = Calendar.getInstance();
try {
cal.setTime(formatter.parse(datetime));
eventdate = cal.get(Calendar.YEAR)+"/"+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.DAY_OF_MONTH)+" "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);
//Log.e("Event date ", eventdate);
} catch (Exception e) {
Log.e("Catch ", "",e);
}
ContentValues event = new ContentValues();
event.put("calendar_id", 3);
event.put("_id", eventid);
event.put("title", mytitle);
event.put("description", mydescription);
event.put("eventTimezone", TimeZone.getDefault().getID());
event.put("dtstart", cal.getTimeInMillis());
event.put("dtend", cal.getTimeInMillis()+60*60*1000);
event.put("hasAlarm", 1); // 0 for false, 1 for true
String eventUriString = "content://com.android.calendar/events";
Uri eventUri = getApplicationContext()
.getContentResolver()
.insert(Uri.parse(eventUriString), event);
System.out.println("event"+eventUri);
}
the following code adds event to my HTC phone running android lollipop but it returns null on Phones like Micromax and Samsung running android Jellybean. What can be the reason for this behavior? Do I need to turn anything on from settings?
try using the constants provided by the Events class.
ContentResolver cr = yourContext.getContentResolver();
ContentValues event = new ContentValues();
event.put(Events.DTSTART, cal.getTimeInMillis());
event.put(Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
event.put(Events.TITLE, mytitle);
event.put(Events.DESCRIPTION, mydescription);
event.put(Events.CALENDAR_ID, calID);
event.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
...
Uri uri = cr.insert(Events.CONTENT_URI, event);
The Event id of this inserted event can be get from this method
long eventID = Long.parseLong(uri.getLastPathSegment());
Check the title Adding Events in Calendar Provider
http://developer.android.com/guide/topics/providers/calendar-provider.html
If you want to insert an _id to the Event, you should check if it is already there
Uri event = ContentUris.withAppendedId(Events.CONTENT_URI, _id);
Cursor cursor = managedQuery(event, null, null, null);
if (cursor.getCount() == 1) {
//the event exists.. so may be you want to update it
} else {
// you can insert your id
}
Actually i am get stuck in a big problem..I have created an app from which i can save event in my device calendar..Now when i save new events from my app in my device calendar it will always delete the events save previously by my app and save a new event and so on..so all works fine..now the big problem is that while deleting it will delete all the events of the calendar that are present in the device calendar including the events that are save by my app..so what i want is to delete only that event that are put by my app while inserting new event from my app not that are already present or which are directly assigned by me in device calendar..so can anyone please help me out to resolve this problem..the code i have use for inserting and deleting are..
Resources res = c.getResources();
Uri EVENTS_URI = Uri.parse("content://com.android.calendar/" + "events");
Uri REMINDERS_URI = Uri.parse("content://com.android.calendar/" + "reminders");
ContentResolver cr = c.getContentResolver();
Uri uri= ContentUris.withAppendedId(EVENTS_URI, 1);
deleteEvent(cr, Resources res = c.getResources();
Uri EVENTS_URI = Uri.parse("content://com.android.calendar/" + "events");
Uri REMINDERS_URI = Uri.parse("content://com.android.calendar/" + "reminders");
ContentResolver cr = c.getContentResolver();
//Deleting event from device calendar before saving new event
deleteEvent(cr, EVENTS_URI, 1);
//saving new data to calendar
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", str);
values.put("description", m_strDescription);
values.put("dtstart", cal.getTimeInMillis());
values.put("dtend", cal.getTimeInMillis());
values.put("hasAlarm", 1);
Uri event = cr.insert(EVENTS_URI, values);
values = new ContentValues();
values.put("event_id", Long.parseLong(event.getLastPathSegment()));
values.put("method", 1);
values.put("minutes", 10);
cr.insert(REMINDERS_URI, values);
Functions for deleting event
private void deleteEvent(ContentResolver resolver, Uri eventsUri, int calendarId)
{
Cursor cursor;
if (android.os.Build.VERSION.SDK_INT <= 7)
{
cursor = resolver.query(eventsUri, new String[]{ "_id" }, "Calendars_id=" + calendarId, null, null);
}
else
{
cursor = resolver.query(eventsUri, new String[]{ "_id" }, "calendar_id=" + calendarId, null, null);
}
while(cursor.moveToNext())
{
long eventId = cursor.getLong(cursor.getColumnIndex("_id"));
resolver.delete(ContentUris.withAppendedId(eventsUri, eventId), null, null);
}
cursor.close();
}
The code you are using is deleting EVERY event: you need to save the ID of the event you create and only delete that one event. When you do this:
cr.insert(REMINDERS_URI, values);
change that to this:
Uri u = cr.insert(REMINDERS_URI, values);
This will save the URI of the event you create. You can then pass that URI into your deleteEvent method to only delete that one event, rather than all events.
I am new to android development world. I want to add one event into my native calendar, I can see the operation successfully, however when I go to Calendar I can not see that. My codes are below
String [] projection = new String [] {"_id", "name"};
Uri calendars = Uri.parse("content://com.android.calendar/calendars");
Cursor c = managedQuery(calendars, projection, "selected=1", null, null);
if(c.moveToFirst()){
String calName;
String calID;
int nameColumn = c.getColumnIndex("name");
int idColumn = c.getColumnIndex("_id");
calName = c.getString(nameColumn);
calID = c.getString(idColumn);
Time start = new Time("20110416T090000");
Time end = new Time("20110416T100000");
ContentValues values = new ContentValues();
values.put("calendar_id", calID);
values.put("title", "Event Title");
values.put("description", "test d");
values.put("eventLocation", "Melbourne");
values.put("dtstart", start.toMillis(true));
values.put("dtend", end.toMillis(true));
values.put("allDay", 0);
values.put("eventStatus", 1);
values.put("transparency", 0);
values.put("visibility", 0);
values.put("hasAlarm", 1);
Uri events = Uri.parse("content://com.android.calendar/events");
Uri result = getContentResolver().insert(events, values);
I use Motorola unit. Can anybody point out why I am failed? Thanks a lot.
I have used the following ContentValues in my own projects and been successful:
ContentValues cv = new ContentValues();
cv.put("calendar_id", calendarid);
cv.put("title", "sometitle");
cv.put("dtstart", ""+calendarfrom.getTimeInMillis());
cv.put("dtend", ""+calendarto.getTimeInMillis());
cv.put("hasAlarm", 0);
Uri newevent = getContentResolver().insert(Uri.parse("content://calendar/events"), cv);
I suspect one of the contentvalues you are providing is causing the failure. Try my simplified example first.
My objective is to read and write Calendar.
i am able to read data from the content://calendar/calendars and content://calendar/events
String uriString = "content://calendar/calendars";
Log.i("INFO", "Reading content from " + uriString);
readContent(uriString);
uriString = "content://calendar/events";
Log.i("INFO", "Reading content from " + uriString);
readContent(uriString);
private void readContent(String uriString) {
Uri uri = Uri.parse(uriString);
Cursor cursor = mContext.getContentResolver().query(uri, null, null,
null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
String columnNames[] = cursor.getColumnNames();
String value = "";
String colNamesString = "";
do {
value = "";
for (String colName : columnNames) {
value += colName + " = ";
value += cursor.getString(cursor.getColumnIndex(colName))
+ " ||";
}
Log.e("INFO : ", value);
} while (cursor.moveToNext());
}
}
i am also inserting new record in the calendar like :
String calUriString = "content://calendar/calendars";
ContentValues values = new ContentValues();
values.put("name", "Code Generate Calendar");
values.put("displayName", "Code Generate Calendar");
values.put("hidden", 0);
values.put("color", "-7581685");
values.put("access_level", "700");
values.put("selected", "1");
values.put("timezone", "Asia/Karachi");
Uri calendarUri = context.getContentResolver().insert(
Uri.parse(calUriString), values);
but it is not appearing in the Calendar.
when i going to insert new events in Calendar like :
ContentValues values = new ContentValues();
values.put("calendar_id", 4);
values.put("dtend", "1277337600000");
values.put("dtstart", "1277251200000");
// values.put("title", "first TEst event");
values.put("transparency", 1);
values.put("selected", 1);
values.put("color", "-16380578");
// values.put("lastDate", "6/25/2010");
//values.put("access_level", 700);
values.put("eventStatus", 1);
values.put("eventTimezone", "UTC");
values.put("timezone", "Asia/Karachi");
values.put("allDay", 1);
String eventUriString = "content://calendar/events";
Uri eventUri = context.getContentResolver().insert(
Uri.parse(eventUriString), values);
throwing exception that column is invalid.
how this possible.
Thanks
The calendar content provider is not part of the Android SDK. It has changed between Android releases before and will do so again. It may not work on some devices where they have replaced the default calendar application with their own.
Do not use undocumented content providers.
The solution is the same as the question you asked 32 minutes previously -- use the Google Calendar GData APIs to manipulate the user's calendar.
// To insert event to the calender for android 2.2 and above if less then 2.2 instead of content://com.android.calendar write content://calendar
String calUriString = "content://com.android.calendar/events";
ContentValues values = new ContentValues();
values.put("calendar_id",2); //id, We need to choose from our mobile for primary its 1
values.put("title", "Birthday");
values.put("description", "Go home at 2pm");
values.put("eventLocation", "Home");
long startTime = System.currentTimeMillis() + 1000 * 60 * 60*24; // Next day
values.put("dtstart", startTime);
values.put("dtend", startTime);
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
values.put("eventStatus", 1); // This information is sufficient for most entries tentative (0), confirmed (1) or canceled (2):
values.put("visibility", 3); // visibility to default (0), confidential (1), private (2), or public (3):
values.put("transparency", 0); // You can control whether an event consumes time opaque (0) or transparent (1).
values.put("hasAlarm", 1); // 0 for false, 1 for true
Uri calendarUri = getApplicationContext().getContentResolver().insert(Uri.parse(calUriString), values);
Dates have been passed since the first question. And today it seems like calendar content provider is well documented. (Maybe since API 14?)
For the short answer to the exception is the difference of the type you give to the column and the type expected. (long expected for dtstart instead of String)
http://developer.android.com/reference/android/provider/CalendarContract.EventsColumns.html#DTSTART
For more information, there is another resource on developer.android.com:
http://developer.android.com/guide/topics/providers/calendar-provider.html