Android : Error in Add event of Calender : Unkown URL - java

I have working in android calender. i have add event in Calender programmatically using android app.
I have Also Refer this links :IllegalArgumentException: Unknown URL content://com.android.calendar/events when inserting an event to the calendar on Android
Adding events to native calendar is not working
but is not working in my code .
my Code is:
ContentValues contentEvent = new ContentValues();
// Particular Calendar in which we need to add Event
contentEvent.put("calendar_id", AlarmId);
// Title/Caption of the Event
contentEvent.put("title", "Wedding");
// Description of the Event
contentEvent.put("description", "Wedding Party");
// Venue/Location of the Event
contentEvent.put("eventLocation", "New York");
// Start Date of the Event with Time
contentEvent.put("dtstart", l);
// End Date of the Event with Time
contentEvent.put("dtend", l+60*1000);
// All Day Event
contentEvent.put("allDay", 1);
// Set alarm for this Event
contentEvent.put("hasAlarm",1);
contentEvent.put("eventTimezone", android.text.format.Time.getCurrentTimezone());
Uri eventsUri = getCalendarURI(false);
// event is added successfully
getContentResolver().insert(eventsUri, contentEvent);
// Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
public Uri getCalendarURI(boolean eventUri) {
Uri calendarURI = null;
if (android.os.Build.VERSION.SDK_INT <= 7) {
calendarURI = (eventUri) ? Uri.parse("content://calendar/events")
: Uri.parse("content://calendar/calendars");
} else {
calendarURI = (eventUri) ? Uri
.parse("content://com.android.calendar/events") : Uri
.parse("content://com.android.calendar/calendars");
}
return calendarURI;
}
My issue Is: When i have run my application that time this error have been generated. so how can i solve this error ?
error is:
java.lang.IllegalArgumentException: Unknown URL content://com.android.calendar/
thank you in Advance

Calendar cal = Calendar.getInstance();
long l = cal.getTimeInMillis();
long cal_Id = 1;
**// Also Here Use Cal_Id = 1 not parse another value**
ContentResolver CR = getContentResolver();
ContentValues calEvent = new ContentValues();
calEvent.put(CalendarContract.Events.CALENDAR_ID, cal_Id); // XXX pick)
calEvent.put(CalendarContract.Events.TITLE, " Demo Data");
calEvent.put(CalendarContract.Events.DTSTART,l);
calEvent.put(CalendarContract.Events.DTEND, l+60 * 1000);
calEvent.put(CalendarContract.Events.EVENT_TIMEZONE, "Indian/Christmas");
// Here use the proper time zone of area wise and solve this error
Uri uri = CR.insert(URL, calEvent);
int id = Integer.parseInt(uri.getLastPathSegment());
Toast.makeText(this, "Created Calendar Event " + id,
Toast.LENGTH_SHORT).show();

try this :
Uri calendars = getCalendarURI(true);
public Uri getCalendarURI(boolean eventUri) {
Uri calendarURI = null;
if (android.os.Build.VERSION.SDK_INT <= 7) {
calendarURI = (eventUri) ? Uri.parse("content://calendar/events")
: Uri.parse("content://calendar/calendars");
} else {
calendarURI = (eventUri) ? Uri
.parse("content://com.android.calendar/events") : Uri
.parse("content://com.android.calendar/calendars");
}
return calendarURI;
}

You can try this way :
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
or you can find in this topic:
How to add calendar events in Android?

Related

How to retrieve lastly added events in android calendar

According to my requirements i should save the events in android calendar like event name, starDate and endDate etc and retrieve lastly saved events, Now everything goes well, instead of fetching last event values i'm getting first event, can anybody tell the logic for this issue please.
Here's my code
private void addEvent2() {
Intent l_intent = new Intent(Intent.ACTION_EDIT);
l_intent.setType("vnd.android.cursor.item/event");
//l_intent.putExtra("calendar_id", m_selectedCalendarId); //this doesn't work
l_intent.putExtra("title", "roman10 calendar tutorial test");
l_intent.putExtra("description", "This is a simple test for calendar api");
l_intent.putExtra("eventLocation", "#home");
l_intent.putExtra("beginTime", System.currentTimeMillis());
l_intent.putExtra("endTime", System.currentTimeMillis() + 1800*1000);
l_intent.putExtra("allDay", 0);
//status: 0~ tentative; 1~ confirmed; 2~ canceled
l_intent.putExtra("eventStatus", 1);
//0~ default; 1~ confidential; 2~ private; 3~ public
l_intent.putExtra("visibility", 3);
//0~ opaque, no timing conflict is allowed; 1~ transparency, allow overlap of scheduling
l_intent.putExtra("transparency", 0);
//0~ false; 1~ true
l_intent.putExtra("hasAlarm", 1);
try {
startActivity(l_intent);
} catch (Exception e) {
Toast.makeText(this.getApplicationContext(), "Sorry, no compatible calendar is found!", Toast.LENGTH_LONG).show();
}
}
Retrieving code
private void getLastEvent() {
Uri l_eventUri;
if (Build.VERSION.SDK_INT >= 8) {
l_eventUri = Uri.parse("content://com.android.calendar/events");
} else {
l_eventUri = Uri.parse("content://calendar/events");
}
String[] l_projection = new String[]{"title", "dtstart", "dtend"};
Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection, "calendar_id=" + m_selectedCalendarId, null, "dtstart DESC, dtend DESC");
//Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection, null, null, null);
if (l_managedCursor.moveToFirst()) {
int l_cnt = 0;
String l_title;
String l_begin;
String l_end;
StringBuilder l_displayText = new StringBuilder();
int l_colTitle = l_managedCursor.getColumnIndex(l_projection[0]);
int l_colBegin = l_managedCursor.getColumnIndex(l_projection[1]);
int l_colEnd = l_managedCursor.getColumnIndex(l_projection[1]);
do {
l_title = l_managedCursor.getString(l_colTitle);
l_begin = getDateTimeStr(l_managedCursor.getString(l_colBegin));
l_end = getDateTimeStr(l_managedCursor.getString(l_colEnd));
l_displayText.append(l_title + "\n" + l_begin + "\n" + l_end + "\n----------------\n");
++l_cnt;
} while (l_managedCursor.moveToNext() && l_cnt < 1);
m_text_event.setText(l_displayText.toString());
}
l_managedCursor.close();
}
retrieve lastly saved events
As long as you don't save the date where you add the event you can't get last added events.
Looking in Calendar.Contract.Events API I can't find any field to insert this kind of extra data, so you have 2 sol.lutions:
Create a SharedPreferences or DataBase to store basic data to find a calendar event PLUS adding date, then make search in this Preferences or DataBase and retrieve information from calendar according to it.
EASIER, BUT NOT RECOMMENDEDAdd in some String field like DESCRIPTION or ORGANIZER the Timestamp or Date of addition of the event, then when searching just get this part of the event and sort to get last added.

Showing google calendar and adding event to it

Is following scenario possible to implement in android app?
Show google calendar to user.
If user is trying to add event fields like title, place etc. are already defined. Only thing he need to do is click 'save' to add event to calendar.
you can use an intent to start the calender event screen
//all version of android
Intent i = new Intent();
// mimeType will popup the chooser any for any implementing application (e.g. the built in calendar or applications such as "Business calendar"
i.setType("vnd.android.cursor.item/event");
// the time the event should start in millis. This example uses now as the start time and ends in 1 hour
i.putExtra("beginTime", new Date().getTime());
i.putExtra("endTime", new Date().getTime() + DateUtils.HOUR_IN_MILLIS);
// the action
i.setAction(Intent.ACTION_EDIT);
startActivity(i);
as taken from:how can i open the calendar from my app?
otherwise if you want to push the data without opening the calendar you can try and use the calendar provider check the documantation: http://developer.android.com/guide/topics/providers/calendar-provider.html (examlple in the edit below)
update according to the comment:
do the folowing -
1)use the calendar provider to query for events:
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();
// Run query
Cursor cur = null;
ContentResolver cr = getContentResolver();
Uri uri = Events.CONTENT_URI;
String selection = "((" + Events.DTSTART + " >= ?) AND ("
+ Events.DTEND + " <= ?))";
String[] selectionArgs = new String[] {startMillis +"", endMillis +""};
// Submit the query and get a Cursor object back.
cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
2)show result using a listView or a gridView use the cursor in a simple adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cur,
new String[] { Events.TITLE, [more fileds you want] },
new int[] { android.R.id.text1 });
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
3)under the list have a button for open event once pressed do :
long calID = 3;
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();
...
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startMillis);
values.put(Events.DTEND, endMillis);
values.put(Events.TITLE, "Jazzercise");
values.put(Events.DESCRIPTION, "Group workout");
values.put(Events.CALENDAR_ID, calID);
values.put(Events.EVENT_TIMEZONE, "America/Los_Angeles");
Uri uri = cr.insert(Events.CONTENT_URI, values);
// get the event ID that is the last element in the Uri
long eventID = Long.parseLong(uri.getLastPathSegment());
//
// ... do something with event ID
//
note that you need the calendar id - you can query for that as well and make the user choose it the first time he opens your app. again its all in the calendar provider documentation

Select specific Calendar when using Java API to create calendar entry

I have successfully created calendar entries using the Java .jar files for Google Calendar API. They always go into the "Rifle" calendar even though I have the calendars shown below. I need to know how to specify the calendar that entry falls under. For example, where would I specify "Meetings" or "Shotgun"
I'm not seeing anything or any examples of how to specify a particular calendar.
public void create() {
try {
CalendarService myService = new CalendarService("My Service");
myService.setUserCredentials("mycalendar", "mypassword");
URL postUrl = new URL("http://www.google.com/calendar/feeds/myurl#junk.com/private/full");
CalendarEventEntry myEntry = new CalendarEventEntry();
//myEntry.setIcalUID("Rec Fire");
DateTime startTime = DateTime.parseDateTime("2014-06-22T09:00:00");
DateTime endTime = DateTime.parseDateTime("2014-06-22T13:00:00");
When eventTimes = new When();
eventTimes.setStartTime(startTime);
eventTimes.setEndTime(endTime);
myEntry.addTime(eventTimes);
Where eventLocation = new Where();
eventLocation.setLabel("R-4");
eventLocation.setValueString("value string");
eventLocation.setRel("REL");
myEntry.addLocation(eventLocation);
EventWho eventWho = new EventWho();
eventWho.setAttendeeStatus("attendee status");
eventWho.setAttendeeType("Meetings");
eventWho.setValueString("who value string");
eventWho.setEmail("myemailt#email.com");
eventWho.setRel("who rel");
myEntry.addParticipant(eventWho);
myEntry.setTitle(new PlainTextConstruct("R-4 Rifles Only"));
myEntry.setContent(new PlainTextConstruct("Paragraph HURST MULLINS"));
CalendarEventEntry insertedEntry = myService.insert(postUrl, myEntry);
} catch (Exception e) {
e.printStackTrace();
}
I figured this out. First you have to get the IDs of your secondary calendars
public void retrieve() {
try {
CalendarService myService = new CalendarService("QuanticoShootingclub");
myService.setUserCredentials("calendar#quanticoshootingclub.com", "washington13");
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
System.out.println("Your calendars:");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
System.out.println("\t\t" + entry.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
}
You can also do this by goign to your Google Calendar on the web. Click the drop-down and then Calendar Settings > Calendar Address: (Calendar ID: #group.calendar.google.com)
Then, when you're creating the new calendar entry, you substitute this ID for the primary ID.
NOTE: From the original code
URL postUrl = new URL("http://www.google.com/calendar/feeds/***<secondary calendar ID>***/private/full");

How to create an Android Calendar event that ends X days from today

I am working on an android app that has a follow-up feature.
People will be able to put in some information including a description and the number of days in the future they want this event to start (IE 1 day, 10 days, 20 days) and then click the create button to create it.
The problem I am having is that I want the date to start X number of days in the future where X is the number of days in the future where it would start(an int passed in of days, IE 1 day, 10 days).
Here is my code:
//Create Calendar event
public void CreateEvent(){
//Variables title, location, description, and days_from_now are all defined elsewhere
Calendar mycal = Calendar.getInstance();
Intent calIntent = new Intent(Intent.ACTION_INSERT);
calIntent.setType("vnd.android.cursor.item/event");
//Put information in
calIntent.putExtra(Events.TITLE, title);
calIntent.putExtra(Events.EVENT_LOCATION, location);
calIntent.putExtra(Events.DESCRIPTION, description);
**//Increment the date by X days
mycal.add(mycal.DATE, days_from_now );
//Start and end time
long startTime = mycal.getTimeInMillis(); //Convert to milliseconds
long endTime = startTime+900000; //15 minutes
//Put the calculated start and end time into the calIntent Intent
calIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime);
calIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime);**
startActivity(calIntent);
}
Finally got it working! The bolded code is what was missing. Thanks for the ideas guys as they led me to the right code!
simple code:
public void addEvent(long calendarID, String title, long startEvent,
long endEvent, int reminder, String description, long createDate) {
try {
System.out.println("add event to calendar");
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startEvent);
values.put(Events.DTEND, endEvent);
values.put(Events.TITLE, title);
values.put(Events.DESCRIPTION, description);
values.put(Events.CALENDAR_ID, calendarID);
values.put(Events.EVENT_TIMEZONE, Calendar.getInstance()
.getTimeZone().getID());
System.out.println(Calendar.getInstance().getTimeZone().getID());
Uri uri = cr.insert(Events.CONTENT_URI, values);
long eventId = Long.parseLong(uri.getLastPathSegment());
setReminder(cr, eventId, reminder);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setReminder(ContentResolver cr, long eventID, int reminder) {
try {
ContentValues values = new ContentValues();
values.put(Reminders.MINUTES, reminder / 60000);
values.put(Reminders.EVENT_ID, eventID);
values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
Uri uri = cr.insert(Reminders.CONTENT_URI, values);
Cursor c = Reminders.query(cr, eventID,
new String[] { Reminders.MINUTES });
if (c.moveToFirst()) {
System.out.println("calendar"
+ c.getInt(c.getColumnIndex(Reminders.MINUTES)));
}
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}

How to add calendar events to default calendar, silently without Intent, in android 4?

I want to add calendar events programmatically (directly) in android 4+. Is it this possible to be tested on emulator? I don't own an android phone. Some sample code would be appreciated. I read Calendar Provider of android developers but I'm confused. How can I add events to the default calendar of a user? I don't need to be synced.
EDIT: I do not want to launch an event adding Intent. Instead I want to add them completely from code and not launch another activity. I need to be able to test on an emulator that the events will be added to the main calendar of the default user of the device. How do I set up an emulator to view the default calendar of the user?
Here is a working example of what i eventually made it:
ContentResolver cr = ctx.getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, dtstart);
values.put(CalendarContract.Events.TITLE, title);
values.put(CalendarContract.Events.DESCRIPTION, comment);
TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
// Default calendar
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.RRULE, "FREQ=DAILY;UNTIL="
+ dtUntill);
// Set Period for 1 Hour
values.put(CalendarContract.Events.DURATION, "+P1H");
values.put(CalendarContract.Events.HAS_ALARM, 1);
// Insert event to calendar
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
where dtuntil is
SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
Calendar dt = Calendar.getInstance();
// Where untilDate is a date instance of your choice, for example 30/01/2012
dt.setTime(untilDate);
// If you want the event until 30/01/2012, you must add one day from our day because UNTIL in RRule sets events before the last day
dt.add(Calendar.DATE, 1);
String dtUntill = yyyyMMdd.format(dt.getTime());
Ref: Recurrence Rule
I believe the section you are looking for is Using an intent to insert an event. In this section it describes how to create an intent for the event you want to add and then the default calender program on the emulator will respond and add it. You may have to set up a dummy profile so that the calendar program will start if you actually want to see that it receives the correct information.
Code from Android Dev Site:
Calendar beginTime = Calendar.getInstance();
beginTime.set(2012, 0, 19, 7, 30);
Calendar endTime = Calendar.getInstance();
endTime.set(2012, 0, 19, 8, 30);
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, "Yoga")
.putExtra(Events.DESCRIPTION, "Group class")
.putExtra(Events.EVENT_LOCATION, "The gym")
.putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
.putExtra(Intent.EXTRA_EMAIL, "rowan#example.com,trevor#example.com");
startActivity(intent);
Dont Forget to add Permission to Manifest
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
Code from :->Android Dev Site
long calID = 3; // Make sure to which calender you want to add event
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();
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startMillis);
values.put(Events.DTEND, endMillis);
values.put(Events.TITLE, "Hackathon");
values.put(Events.DESCRIPTION, "do some code");
values.put(Events.CALENDAR_ID, calID);
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Uri uri = cr.insert(Events.CONTENT_URI, values);
// get the event ID that is the last element in the Uri
long eventID = Long.parseLong(uri.getLastPathSegment());
Using this code, you can programmatically add an event to device calendar. I have tested in Marshmallow, and it works fine for me.
private void addToDeviceCalendar(String startDate,String endDate, String title,String description, String location) {
String stDate = startDate;
String enDate = endDate;
GregorianCalendar calDate = new GregorianCalendar();
//GregorianCalendar calEndDate = new GregorianCalendar();
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy,MM,dd,HH,mm");
Date date,edate;
try {
date = originalFormat.parse(startDate);
stDate=targetFormat.format(date);
} catch (ParseException ex) {}
long startMillis = 0;
long endMillis = 0;
String dates[] = stDate.split(",");
SD_YeaR = dates[0];
SD_MontH = dates[1];
SD_DaY = dates[2];
SD_HouR = dates[3];
SD_MinutE = dates[4];
/*Log.e("YeaR ", SD_YeaR);
Log.e("MontH ",SD_MontH );
Log.e("DaY ", SD_DaY);
Log.e(" HouR", SD_HouR);
Log.e("MinutE ", SD_MinutE);*/
calDate.set(Integer.parseInt(SD_YeaR), Integer.parseInt(SD_MontH)-1, Integer.parseInt(SD_DaY), Integer.parseInt(SD_HouR), Integer.parseInt(SD_MinutE));
startMillis = calDate.getTimeInMillis();
/*
try {
edate = originalFormat.parse(endDate);
enDate=targetFormat.format(edate);
} catch (ParseException ex) {}
String end_dates[] = endDate.split(",");
String ED_YeaR = end_dates[0];
String ED_MontH = end_dates[1];
String ED_DaY = end_dates[2];
String ED_HouR = end_dates[3];
String ED_MinutE = end_dates[4];
calEndDate.set(Integer.parseInt(ED_YeaR), Integer.parseInt(ED_MontH)-1, Integer.parseInt(ED_DaY), Integer.parseInt(ED_HouR), Integer.parseInt(ED_MinutE));
endMillis = calEndDate.getTimeInMillis();*/
try {
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, startMillis);
values.put(CalendarContract.Events.DTEND, calDate.getTimeInMillis() + 60 * 60 * 1000);
values.put(CalendarContract.Events.TITLE, title);
values.put(CalendarContract.Events.DESCRIPTION, description);
values.put(CalendarContract.Events.EVENT_LOCATION,location);
values.put(CalendarContract.Events.HAS_ALARM,1);
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.EVENT_TIMEZONE, Calendar.getInstance()
.getTimeZone().getID());
System.out.println(Calendar.getInstance().getTimeZone().getID());
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
return;
}
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
long eventId = Long.parseLong(uri.getLastPathSegment());
Log.d("Ketan_Event_Id", String.valueOf(eventId));
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the way to ask user to which calendar the event has to be added. As my requirement was this and didn't find the solution at one place. I have summarized and came up with this solution, hope it helps someone :)
final ContentResolver cr = this.getContentResolver();
Cursor cursor ;
if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), new String[]{ "_id", "calendar_displayName" }, null, null, null);
else
cursor = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
if (cursor != null && cursor.moveToFirst() ) {
final String[] calNames = new String[cursor.getCount()];
final 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();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final long startDate = sdf.parse(slotData.getSlot_date() + " " + slotData.getSlot_from()).getTime();
final long endDate = sdf.parse(slotData.getSlot_date() + " " + slotData.getSlot_to()).getTime();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select any one");
builder.setSingleChoiceItems(calNames, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ContentValues cv = new ContentValues();
cv.put("calendar_id", calIds[which]);
cv.put("title", title);
cv.put("dtstart", startDate);
cv.put("hasAlarm", 1);
cv.put("dtend", endDate);
cv.put("eventTimezone", TimeZone.getDefault().getID());
Uri newEvent ;
if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);
else
newEvent = cr.insert(Uri.parse("content://calendar/events"), cv);
if (newEvent != null) {
long id = Long.parseLong( newEvent.getLastPathSegment() );
ContentValues values = new ContentValues();
values.put( "event_id", id );
values.put( "method", 1 );
values.put( "minutes", 15 ); // 15 minutes
if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
cr.insert( Uri.parse( "content://com.android.calendar/reminders" ), values );
else
cr.insert( Uri.parse( "content://calendar/reminders" ), values );
}
dialog.cancel();
}
});
builder.create().show();
}
if (cursor != null) {
cursor.close();
}
After reading several posts and after a few tries.
I finally found this method to work well on Android 8 and 10.
My code:
public void addEventToCalendar() {
Context myContext = getContext();
String[] projection = {"_id", "calendar_displayName"};
Cursor calCursor = myContext.getContentResolver().query(CalendarContract.Calendars.CONTENT_URI, projection, CalendarContract.Calendars.VISIBLE + " = 1 AND " + CalendarContract.Calendars.IS_PRIMARY + "=1", null, CalendarContract.Calendars._ID + " ASC");
if(calCursor.getCount() <= 0){
calCursor = myContext.getContentResolver().query(CalendarContract.Calendars.CONTENT_URI, projection, CalendarContract.Calendars.VISIBLE + " = 1", null, CalendarContract.Calendars._ID + " ASC");
}
while (calCursor.moveToNext()) {
long id = calCursor.getLong(calCursor.getColumnIndexOrThrow(CalendarContract.Calendars._ID));
long startMillis;
long endMillis;
Calendar beginTime = Calendar.getInstance();
beginTime.set(2021, 9, 22, 15, 30);
startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(2021, 9, 22, 16, 45);
endMillis = endTime.getTimeInMillis();
ContentResolver cr = Objects.requireNonNull(getActivity()).getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, startMillis);
values.put(CalendarContract.Events.DTEND, endMillis);
values.put(CalendarContract.Events.TITLE, "My event");
values.put(CalendarContract.Events.DESCRIPTION, "Nice description");
values.put(CalendarContract.Events.CALENDAR_ID, id);
Log.i("ID","my Id"+ id);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
long eventID = Long.parseLong(uri.getLastPathSegment());
}
}
I was able to test on different phones and the insertion is done on the google calendar as well as on a basic android calendar.
Normally this method makes sure to insert the event (s) in all the calendars available on the device. I couldn't test it but I have high hopes.
Agree with above all answers but import is calender Id. you can not use 1 as samsung phone uses 1 for their calender(S Planner).So calender ID is id for which email you want event. you can get calender id by following code for specific event
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 2 answer
}

Categories