Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
A few days ago , it was working the "Automatically add Google Meet to my calendar events".
Suddenly, It has not worked in Google Calendar API and the "getHangoutLink()" returns "null".
How can I fix it? Help me with some codes.
Thanks in advance.
Use the following code.
Event event = new Event()
.setSummary(title)
.setLocation(location)
.setDescription(description);
DateTime startDateTime = new DateTime( date +"T"+startTime+"+06:00" );//"2020-05-05T11:00:00+06:00");
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone("Asia/Dhaka");
event.setStart(start);
DateTime endDateTime = new DateTime(date +"T"+endTime+"+06:00");//"2020-05-05T12:00:00+06:00");
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone("Asia/Dhaka");
event.setEnd(end);
String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=1"};
event.setRecurrence(Arrays.asList(recurrence));
/* s1 = "abc#gmail.com";
s2 = "xyz#gmail.com";
EventAttendee[] attendees = new EventAttendee[] {
new EventAttendee().setEmail(s1),
new EventAttendee().setEmail(s2),
};*/
EventAttendee attendees[];
attendees = new EventAttendee[allAttendees.size()];
for(int i=0; i<allAttendees.size(); i++){
// System.out.println(allAttendees.get(i));
attendees[i] = new EventAttendee().setEmail(allAttendees.get(i));
}
event.setAttendees(Arrays.asList(attendees));
EventReminder[] reminderOverrides = new EventReminder[] {
new EventReminder().setMethod("email").setMinutes(24 * 60),
new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
.setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);
ConferenceSolutionKey conferenceSKey = new ConferenceSolutionKey();
conferenceSKey.setType("hangoutsMeet"); // Non-G suite user
CreateConferenceRequest createConferenceReq = new CreateConferenceRequest();
createConferenceReq.setRequestId("3whatisup3"); // ID generated by you
createConferenceReq.setConferenceSolutionKey(conferenceSKey);
ConferenceData conferenceData = new ConferenceData();
conferenceData.setCreateRequest(createConferenceReq);
event.setConferenceData(conferenceData);
String calendarId = "primary";
try {
event = service.events().insert(calendarId, event).setConferenceDataVersion(1).execute();
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("Event created: %s\n", event.getHtmlLink());
System.out.printf("Hangout Link %s\n", event.getHangoutLink());
I try to get the ID of email that I just send it through Java EWS API.
My goal is when I got that ID I would store it to Database.
This what I'm trying:
try {
String isiEmail = generateIsiEmail(nmBank, jenis, tglAw, tglAk, produk);
EmailMessage mail = new EmailMessage(service);
mail.setSubject(jdlEmail);
mail.setBody(new MessageBody(isiEmail));
//set to cc
mail.getToRecipients().add(new EmailAddress(from.replaceAll("\\s", "")));
String[] too = to.split("\\;");
for (int i = 0; i <too.length; i++) {
mail.getToRecipients().add(new EmailAddress(too[i].replaceAll("\\s", "")));
}
String[] ccc = cc.split("\\;");
for (int i = 0; i <ccc.length; i++) {
mail.getCcRecipients().add(new EmailAddress(ccc[i].replaceAll("\\s", "")));
}
mail.sendAndSaveCopy();
} catch (ServiceLocalException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Thanks for help.
I solved by my self.
this step what I'm done with.
I use ExtendedPropertyDefinition refer from this tutorial https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/dd633654(v%3dexchg.80) , but I modified from C# into java programing language,
set ExtendedPropertyDefinition then save the uuidToStr to database
UUID uuid = UUID.randomUUID();
ExtendedPropertyDefinition epd = new ExtendedPropertyDefinition(uuid, "NamaId", MapiPropertyType.String);
String uuidToStr = uuid.toString();
String isiEmail = generateIsiEmail(nmBank, jenis, tglAw, tglAk, produk);
EmailMessage mail = new EmailMessage(service);
mail.setSubject(jdlEmail);
mail.setBody(new MessageBody(isiEmail));
//set to cc
mail.getToRecipients().add(new EmailAddress(from.replaceAll("\\s", "")));
String[] too = to.split("\\;");
for (int i = 0; i <too.length; i++){
mail.getToRecipients().add(new EmailAddress(too[i].replaceAll("\\s", "")));
}
String[] ccc = cc.split("\\;");
for (int i = 0; i <ccc.length; i++){
mail.getCcRecipients().add(new EmailAddress(ccc[i].replaceAll("\\s", "")));
}
mail.setExtendedProperty(epd, "isiId");
mail.sendAndSaveCopy();
get the email based on ExtendedPropertyDefinition uuidToStr from database
UUID uuid = UUID.fromString("cc59cdbf-aad4-4cd1-a4f0-e7819c56b884");
ExtendedPropertyDefinition epd = new ExtendedPropertyDefinition(uuid, "NamaId", MapiPropertyType.String);
ItemView view2 = new ItemView(3);
SearchFilter sf = new SearchFilter.IsEqualTo(epd,"isiId");
FindItemsResults<Item> fir = service.findItems(WellKnownFolderName.SentItems, sf, view2);
for (Item itm : fir.getItems()){
System.out.println(itm.getId());
System.out.println(itm.getSubject());
}
DONE;
You should make use of the InternetMessageId property.
Call the FindItems method to search for messages in the sent items folder. Then instantiate an EmailMessage object so you can access the InternetMessageId property:
ItemView view = new ItemView(100); // You can change this to your needs.
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.InternetMessageId);
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.SentItems, view);
foreach (Item item in results)
{
if (item is EmailMessage)
{
EmailMessage emailMsg = item as EmailMessage;
Console.WriteLine(emailMsg.InternetMessageId);
}
}
I am using C# EWS Api, But this logic will work for you.
First you have to Save the email in Draft and then after you can get Email id.
EmailMessage emailMessage = new EmailMessage(service);
emailMessage.From = email.From;
emailMessage.Subject = email.Subject;
emailMessage.Body = new MessageBody(BodyType.HTML, email.Body);
foreach (var toAddress in email.To)
{
emailMessage.ToRecipients.Add(toAddress);
}
// Send message and save copy by default to sentItems folder
emailMessage.Save();
emailMessage.Load();
// Get Email Conversation Id.
string ConversationId = emailMessage.ConversationId.UniqueId;
string EmailMessageId;
emailMessage.SendAndSaveCopy();
// Get Email Message Id by InternetMessageId.
List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
searchFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.InternetMessageId, InternetMessageId));
// Create the search filter.
SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
ItemView view = new ItemView(50);
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.InternetMessageId);
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.SentItems, searchFilter, view);
if (results.Items.Count > 0)
{
Item item = results.Items[0];
EmailMessage message = EmailMessage.Bind(service, item.Id);
EmailMessageId = message.Id.UniqueId;
}
I believe the solution is this:
EmailMessage em = EmailMessage.bind( service, item.getId(),
new PropertySet( EmailMessageSchema.InternetMessageId) );
Explanation :
We have to bind the item to an email message, but instead of grabbing all the info, we only ask for the ID and any additional properties we want through the PropertySet parameter.
found -> Exchange Web Services get Message Message-ID
Actually I have done client side pagination using datatables but now requirement has changed due to large number of records around 100K.
I need to implement server side pagination.
For that I used below code
GSP
$('#data-grid-table').dataTable( {
"processing" : true,
"sAjaxSource": dataUrl,
"serverSide" : true,
"sPaginationType": "full",
"iDisplayLength": 25,
"aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
"scrollX": true,
"bFilter": false,
"columnDefs": [ {
searchable: false,
"orderable": false,
className: "view-cell",
targets: 0
}],
"aaSorting": [[1,'asc']],
"fnDrawCallback": function( oSettings ) {
var callBackFlag = $("#hidden-view-flag").val()
if(callBackFlag=="1"){
$("#hidden-view-flag").val("2")
}
if(callBackFlag == "2"){
$("#hidden-view-flag").val("3")
}
if(hideViewColumn){
$(".view-cell").hide();
}
$('.datasetTable, tbody').find('tr').each(function(){
$(this).find('th:nth-child(1)').removeClass("sorting_asc");
});
}
});
Controller
dbObjArray = new BasicDBObject[2]
dbObjArray[0]= cruxLevel
dbObjArray[1] = project
List<DBObject> pipeline = Arrays.asList(dbObjArray)
if (!datasetObject?.isFlat && jsonFor != 'collection-grid') {
output= dataSetCollection.aggregate(pipeline)
}else{
//def skipRecords = params.iDisplayStart
//def limitRecords = params.iDisplayLength
//println 'params.iDisplayStart' + params.iDisplayStart
//println 'params.iDisplayLength' + params.iDisplayLength
println 'else-====================='
DBObject limit = new BasicDBObject('$limit':10);
DBObject skip = new BasicDBObject('$skip':5);
isFlatOutput = true;
dbObjArray = new BasicDBObject[3]
dbObjArray[0]= project
dbObjArray[1]= skip
dbObjArray[2]= limit
List<DBObject> pipeline1 = Arrays.asList(dbObjArray)
AggregationOptions aggregationOptions = AggregationOptions.builder()
.batchSize(100)
.outputMode(AggregationOptions.OutputMode.CURSOR)
.allowDiskUse(true)
.build();
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
println 'Start time to fetch -------------------------------------' + sdfDate.format(now)
output = dataSetCollection.aggregate(pipeline1,aggregationOptions)
Date now1 = new Date();
println 'End time to fetch-------------------------------' + sdfDate.format(now1)
}
if(isFlatOutput){
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now2 = new Date();
println 'Start time to retrieve-------------------------------' + sdfDate.format(now2)
while(output.hasNext()) {
dataList.add(output.next());
}
Date now3 = new Date();
println 'End time to retrieve-------------------------------' + sdfDate.format(now3)
}
I was not getting how to take limit and skip so I have hard coded it.
Actual result: 10 results are displaying but next is disabled.
Expected result : 10 results should display and fetch next 10 records on click of next button.
Kindly tell me where I am going wrong.
def skipRecords
def limitRecords
if(params.iDisplayStart == null){
skipRecords = 0;
}
if(params.iDisplayLength == null){
limitRecords = 25;
}
def dbObjArrayTotal = new BasicDBObject[1]
dbObjArrayTotal[0]= project
List<DBObject> pipelineTotal = Arrays.asList(dbObjArrayTotal)
AggregationOptions aggregationOptions = AggregationOptions.builder()
.batchSize(100)
.outputMode(AggregationOptions.OutputMode.CURSOR)
.allowDiskUse(true)
.build();
def totalCount = dataSetCollection.aggregate(pipelineTotal,aggregationOptions)
totalCount = totalCount.size()
if(limitRecords == -1){
limitRecords = totalCount
}
DBObject limit = new BasicDBObject('$limit':limitRecords);
DBObject skip = new BasicDBObject('$skip':skipRecords);
dbObjArray = new BasicDBObject[3] dbObjArray[0]= project
dbObjArray[1]= skip
dbObjArray[2]= limit
List<DBObject> flatPipeline = Arrays.asList(dbObjArray)
output = dataSetCollection.aggregate(flatPipeline,aggregationOptions)
def serverData = [
"iTotalRecords" : totalCount,
"iTotalDisplayRecords" : totalCount,
"aaData": yourResult]
return serverData;
And above GSP is correct use as it is.
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");
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
}