Write and read ID of event Android - android

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.

Related

Android - Adding a calendar event without reminder

I'm using the following function to add an event to calendar:
public String addEventToCalendar(long startDate, long endDate, String recurrenceRule, boolean isAllDay, String title, String description, String location, long calendarID) {
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.DTSTART, startDate);
values.put(CalendarContract.Events.DTEND, endDate);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
if (recurrenceRule != null)
values.put(CalendarContract.Events.RRULE, recurrenceRule);
values.put(CalendarContract.Events.TITLE, title);
values.put(CalendarContract.Events.DESCRIPTION, description);
values.put(CalendarContract.Events.CALENDAR_ID, calendarID);
values.put(CalendarContract.Events.ALL_DAY, isAllDay);
values.put(CalendarContract.Events.EVENT_LOCATION, location);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
return null; // we don't have the right permissions
}
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
String eventID = uri.getLastPathSegment();
return eventID;
}
It works, but the resulting calendar event, have a 30 minutes reminder! I'm not able to figure out why. Any clue please?
Thanks a lot.
It seems like a default reminder is added after you insert your calendar event.
What you could try is to check if there are any reminder associated with your event right after you inserted it. And delete it if so.
CalendarContract.Reminders.query(contentResolver, eventId, projection)
will give you a list of reminder associated with the eventId
If the Cursor contains any reminder you can delete it with :
getContentResolver().delete(ContentUris.withAppendedId(CalendarContract.Reminders.CONTENT_URI, reminderId), null, null);
docs : http://developer.android.com/reference/android/provider/CalendarContract.Reminders.html
Try to add this
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.HAS_ALARM, 0);
Whether the event has an alarm or not. Column name.
Type: INTEGER (boolean)
public static final String HAS_ALARM = "hasAlarm";

added events are not showing in calendar app in android

I am using calender provider to insertEvent in google calender . The problem is I am getting the Query result as Uri without any exception and event Id also . But the Event i am adding is not showing in calender app.Can anyone Help me . And i also wanted to set reminder for my event . Below is the code i am using to add event .
public void addNewEvent() {
long startMillis = 0;
long endMillis = 0;
Calendar beginTime = Calendar.getInstance();
beginTime.set(2016, 4, 1, 7, 30);
Log.e("startTime",new SimpleDateFormat("MM:dd:yyyy").format(beginTime.getTimeInMillis()));
startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(2016, 4, 1, 8, 56);
endMillis = endTime.getTimeInMillis();
// Insert Event
Log.e("endTime",new SimpleDateFormat("MM:dd:yyyy").format(endTime.getTimeInMillis()));
ContentResolver cr = activity.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, "Going for a ride");
values.put(CalendarContract.Events.DESCRIPTION, "Event desc");
values.put(CalendarContract.Events.CALENDAR_ID, 39);
values.put(CalendarContract.Events.EVENT_LOCATION,"Malta");
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
// Retrieve ID for new event
long eventID = Long.parseLong(uri.getLastPathSegment());
setReminder(cr, eventID, 100);
Log.e("eventId",eventID+"");
}
public void setReminder(ContentResolver cr, long eventID, int timeBefore) {
try {
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, timeBefore);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
Cursor c = CalendarContract.Reminders.query(cr, eventID,
new String[]{CalendarContract.Reminders.MINUTES});
if (c.moveToFirst()) {
Log.e("Reminder Uri",uri.toString());
Log.e("","calendar"
+ c.getInt(c.getColumnIndex(CalendarContract.Reminders.MINUTES)));
}
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
above code helps in adding events to phone calendar only.if you want to add events to google calendar then you have to use google calendar api. when adding events to phone calendar i have set calendar id to "1".

Event not being added to Calendar on some Android phones

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
}

Android Insert Calendar Intent - Without alarm/reminder

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);

Read and write Calendar

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

Categories

Resources