1

I am quite new to android.I am developing one App in Which I ant to set events automatically. this is my Code ,I am referring http://developer.android.com/guide/topics/providers/calendar-provider.html

public boolean setReminder(int SelectedHour,int SelectedMinute,int NewHour,int NewMinute)
{
    try{
        long calID = 3;
        long startMillis = 0;
        long endMillis = 0;
        Calendar StartTime = Calendar.getInstance();
        StartTime.set(StartTime.YEAR,StartTime.MONTH,StartTime.DAY_OF_MONTH,SelectedHour,SelectedMinute);
        startMillis = StartTime.getTimeInMillis();
        Calendar EndTime = Calendar.getInstance();
        int NewMonth = StartTime.MONTH+1;int NewDay = StartTime.DAY_OF_MONTH;
        EndTime.set(StartTime.YEAR,NewMonth,NewDay,NewHour,NewMinute);
        endMillis = EndTime.getTimeInMillis();

        TimeZone tz = TimeZone.getDefault();

        ContentResolver cr = getContentResolver();
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Events.DTSTART, startMillis);
        values.put(CalendarContract.Events.DTEND, endMillis);
        values.put(CalendarContract.Events.TITLE, "Jazzercise");
        values.put(CalendarContract.Events.DESCRIPTION, "Group workout");
        values.put(CalendarContract.Events.CALENDAR_ID, calID);
        values.put(CalendarContract.Events.EVENT_TIMEZONE,  tz.getID());
        //Getting Problem in Line Below 
        Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI,values);
        // get the event ID that is the last element in the Uri
        long eventID = Long.parseLong(uri.getLastPathSegment());


        Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
        builder.appendPath("time");
        ContentUris.appendId(builder, startMillis);
        Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
        startActivity(intent);
   return true;
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
        return false;
    }

I am getting RedMark below the Line

Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI,values);

error is saying Call requires permission which may be rejected by user.code should explicitly check to see if permission is available...

I hav already added permissions like android.permission.ACCESS_FINE_LOCATION and android.permission.ACCESS_COARSE_LOCATION in my manifest File

though my Application runs but when i call the Calender Intent it gives me Webpage Not Availble.

I also tried like Adding events date and time in android calendar

but still its not working.

thanks in advance..

Community
  • 1
  • 1
Pranita
  • 803
  • 7
  • 16
  • why you add `Location` permission in your manifeast..? – Abhishek Patel May 16 '16 at 09:18
  • check this ref :http://stackoverflow.com/questions/22990189/content-provider-grant-uri-permission?rq=1 – Damini Mehra May 16 '16 at 09:21
  • which permissions i need to add in Manifest??? I also Added **android.permission.READ_CALENDAR** and **android.permission.WRITE_CALENDAR**.why its not working?? – Pranita May 16 '16 at 09:21
  • your error "Call requires.." says when you use `API level 23` than you must implement `Runtime Permission` for added permission in your project for more info please visit.http://developer.android.com/training/permissions/requesting.html – Abhishek Patel May 16 '16 at 09:24

4 Answers4

0

This means that you're requesting functionality that in android >=6 may ask for Runtime Permissions - the permission that user must allow to your app at runtime. Please follow link to learn how to implement correct flow.

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CALENDAR)
        != PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.READ_CALENDAR)) {

    // Show an expanation to the user *asynchronously* -- don't block
    // this thread waiting for the user's response! After the user
    // sees the explanation, try again to request the permission.

} else {

    // No explanation needed, we can request the permission.

    ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.READ_CALENDAR},
            MY_PERMISSIONS_REQUEST_READ_CALENDAR;

    // MY_PERMISSIONS_REQUEST_READ_CALENDAR is an
    // app-defined int constant. The callback method gets the
    // result of the request.
}
}else{

Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI,values);

}
Evgeniy Mishustin
  • 3,343
  • 3
  • 42
  • 81
0

Probably you are getting this error because of the lack of the Calendar permission. Add Calendar permission into your Manifest file.

To read from the Calendar:

android.permission.READ_CALENDAR

To write into the Calendar:

android.permission.WRITE_CALENDAR

SpiralDev
  • 7,011
  • 5
  • 28
  • 42
0

Since this still seems to be a problem to many coders... Here my solution: I have a button to start the interaction with the calendar. This will first open a Message Box with 2 Buttons where the User has to allow further actions. If he allows another Messagebox will appear and asks the user for permission to read the calendar

private void addMessageBox() {
    AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(getContext());
    dlgAlert.setMessage("Events mit lokalem Kalender synchronisieren?");
    dlgAlert.setTitle("Zugriff auf Kalender");
    dlgAlert.setCancelable(true);


    dlgAlert.setPositiveButton("Erlauben",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    permissions = new Permissions(getActivity());
                    if (!permissions.checkPermissionReadCalendar()) {
                        permissions.requestPermissionReadCalendar(Permissions.CALENDAR_PERMISSION_REQUEST_READ);
                    } else {
                        try {
                            addToLocalCalendar();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
    dlgAlert.setNegativeButton("Verbieten",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    //return true;
                }
            });

    dlgAlert.create().show();
}

I control the permissions with a custom class i found somewhere in this forum:

Permissions permissions;

With the class:

public class Permissions {


public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_WRITE = 0;
public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_READ = 1;
public static final int CALENDAR_PERMISSION_REQUEST_READ = 2;

Activity activity;
Context mContext;

public Permissions(Activity activity) {
    this.activity = activity;
    this.mContext = activity;
}



public boolean checkPermissionReadCalendar(){
    int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_CALENDAR);
    if (result == PackageManager.PERMISSION_GRANTED){
        return true;
    } else {
        return false;
    }
}

public void requestPermissionReadCalendar(int requestCode){
    if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.READ_CALENDAR)){
        Toast.makeText(mContext.getApplicationContext(), "Kalenderzugriff nicht möglich. Bitte erlaube Kalenderzugriff in den App Einstellungen.", Toast.LENGTH_LONG).show();
    } else {
        ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.READ_CALENDAR},requestCode);
    }
}

U somehow do not need to ask for the write permission... In the App settings there is only one permission for the calendar and it will be allowed if u call the read or write permission. In the manifest add this:

<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />

If the user rejects the permission he will always get the toast message that he has not enough rights to do this action. He has to allow the permission in the App settings manually. And for the red underlined part.. It says that the App has to check if the user allows the following action. If u click on this line and hit Alt+Enter this code will be inserted:

   if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return true;
    }

This checks if the App has permission and returns if not.

HansLager
  • 1
  • 4
0

We need to check and request both permissions.

  if (ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(activity!!, arrayOf(Manifest.permission.READ_CALENDAR), 30);
    }

   if (ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(activity!!, arrayOf(Manifest.permission.WRITE_CALENDAR), 35);
    }

If we requested both READ and WRITE Calendar permission. this error will not come again.