I want to save an event in the calendar directly, without openning the calendar app. I have found that in some devices the event is not saved in calendar, but I am not getting any error in the logcat. This is the code that I am using,
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues()
values.put(CalendarContract.Events.DTSTART, DateBuilder.getStartDayCalendar());
values.put(CalendarContract.Events.DTEND, DateBuilder.getEndDayCalendar());
values.put(CalendarContract.Events.TITLE, "Title");
values.put(CalendarContract.Events.DESCRIPTION, "description");
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
Does anyone know what is happening?
Thanks!
UPDATE
In same devices you need to set up the status,Events.STATUS, Events.STATUS_CONFIRMED
, that was the problem
Find the solution :
Follow the steps it will create event directly :
Manifest.xml
Add permissions in Manifest
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="testpreference.com.testcalendar.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calendars" />
<Spinner
android:id="@+id/calendarid_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/newevent_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Event"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Spinner calendarIdSpinner;
private Hashtable<String,String> calendarIdTable;
private Button newEventButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendarIdSpinner = (Spinner) findViewById(R.id.calendarid_spinner);
newEventButton = (Button) findViewById(R.id.newevent_button);
newEventButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (CalendarHelper.haveCalendarReadWritePermissions(MainActivity.this))
{
addNewEvent();
}
else
{
CalendarHelper.requestCalendarReadWritePermission(MainActivity.this);
}
}
});
calendarIdSpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
if (CalendarHelper.haveCalendarReadWritePermissions(this))
{
//Load calendars
calendarIdTable = CalendarHelper.listCalendarId(this);
updateCalendarIdSpinner();
}
}
private void updateCalendarIdSpinner()
{
if (calendarIdTable==null)
{
return;
}
List<String> list = new ArrayList<String>();
Enumeration e = calendarIdTable.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
list.add(key);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
calendarIdSpinner.setAdapter(dataAdapter);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode==CalendarHelper.CALENDARHELPER_PERMISSION_REQUEST_CODE)
{
if (CalendarHelper.haveCalendarReadWritePermissions(this))
{
Toast.makeText(this, (String)"Have Calendar Read/Write Permission.",
Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void addNewEvent()
{
if (calendarIdTable==null)
{
Toast.makeText(this, (String)"No calendars found. Please ensure at least one google account has been added.",
Toast.LENGTH_LONG).show();
//Load calendars
calendarIdTable = CalendarHelper.listCalendarId(this);
updateCalendarIdSpinner();
return;
}
final long oneHour = 1000 * 60 * 60;
final long tenMinutes = 1000 * 60 * 10;
long oneHourFromNow = (new Date()).getTime() + oneHour;
long tenMinutesFromNow = (new Date()).getTime() + tenMinutes;
String calendarString = calendarIdSpinner.getSelectedItem().toString();
int calendar_id = Integer.parseInt(calendarIdTable.get(calendarString));
CalendarHelper.MakeNewCalendarEntry(this, "Test", "Add event", "Somewhere",tenMinutesFromNow,tenMinutesFromNow+oneHour,false,true,calendar_id,3);
}
}
Create class for calendar selection
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
private static final String TAG = "OnItemSelectedListener";
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.v(TAG,"onNohingSelected() called.");
}
}
CalendarHelper.java
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.TimeZone;
public class CalendarHelper {
//Remember to initialize this activityObj first, by calling initActivityObj(this) from
//your activity
private static final String TAG = "CalendarHelper";
public static final int CALENDARHELPER_PERMISSION_REQUEST_CODE = 99;
public static void MakeNewCalendarEntry(Activity caller,String title,String description,String location,long startTime,long endTime, boolean allDay,boolean hasAlarm, int calendarId,int selectedReminderValue) {
ContentResolver cr = caller.getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startTime);
values.put(Events.DTEND, endTime);
values.put(Events.TITLE, title);
values.put(Events.DESCRIPTION, description);
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.STATUS, Events.STATUS_CONFIRMED);
if (allDay)
{
values.put(Events.ALL_DAY, true);
}
if (hasAlarm)
{
values.put(Events.HAS_ALARM, true);
}
//Get current timezone
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Log.i(TAG, "Timezone retrieved=>"+TimeZone.getDefault().getID());
Uri uri = cr.insert(Events.CONTENT_URI, values);
Log.i(TAG, "Uri returned=>"+uri.toString());
// get the event ID that is the last element in the Uri
long eventID = Long.parseLong(uri.getLastPathSegment());
if (hasAlarm)
{
ContentValues reminders = new ContentValues();
reminders.put(Reminders.EVENT_ID, eventID);
reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
reminders.put(Reminders.MINUTES, selectedReminderValue);
Uri uri2 = cr.insert(Reminders.CONTENT_URI, reminders);
}
}
public static void requestCalendarReadWritePermission(Activity caller)
{
List<String> permissionList = new ArrayList<String>();
if (ContextCompat.checkSelfPermission(caller,Manifest.permission.WRITE_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
{
permissionList.add(Manifest.permission.WRITE_CALENDAR);
}
if (ContextCompat.checkSelfPermission(caller,Manifest.permission.READ_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
{
permissionList.add(Manifest.permission.READ_CALENDAR);
}
if (permissionList.size()>0)
{
String [] permissionArray = new String[permissionList.size()];
for (int i=0;i<permissionList.size();i++)
{
permissionArray[i] = permissionList.get(i);
}
ActivityCompat.requestPermissions(caller,
permissionArray,
CALENDARHELPER_PERMISSION_REQUEST_CODE);
}
}
public static Hashtable listCalendarId(Context c) {
if (haveCalendarReadWritePermissions((Activity)c)) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst())
{
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String,String> calendarIdTable = new Hashtable<>();
do
{
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName,calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
return null;
}
public static boolean haveCalendarReadWritePermissions(Activity caller)
{
int permissionCheck = ContextCompat.checkSelfPermission(caller,
Manifest.permission.READ_CALENDAR);
if (permissionCheck== PackageManager.PERMISSION_GRANTED)
{
permissionCheck = ContextCompat.checkSelfPermission(caller,
Manifest.permission.WRITE_CALENDAR);
if (permissionCheck== PackageManager.PERMISSION_GRANTED)
{
return true;
}
}
return false;
}
}