0

I'm currently implementing the calendar provider however i've stumbled upon a minor error that i'd like to prevent.

ContentResolver contentResolver = getContentResolver();
ContentValues contentValues = new ContentValues();

....

Uri uri = contentResolver.insert(CalendarContract.Events.CONTENT_URI, contentValues); // Error pops here

"Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential `SecurityException"

What is the best method to prevent this error?

Any help will be appreciated.

WonderfulWonder
  • 515
  • 1
  • 8
  • 20

3 Answers3

4

Handle android permission first , check if they are available , if not you can request them as shown below

proceed with your functionality only if permissions are available

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED 
    && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);}else if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED 
        && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED){

ContentResolver contentResolver = getContentResolver();
ContentValues contentValues = new ContentValues();
Uri uri = contentResolver.insert(CalendarContract.Events.CONTENT_URI, contentValues);}
Ak9637
  • 990
  • 6
  • 12
  • 1
    This is correct, but OP should be aware that he needs to ask for READ_CALENDAR and WRITE_CALENDAR permission. Otherwise he will make a non user-friendly app. OP, you can check the complete doc here https://developer.android.com/training/permissions/requesting.html – andrei_zaitcev Oct 25 '16 at 12:02
  • agreed with @andrei_zaitcev – Ak9637 Oct 25 '16 at 12:05
0

You can always add throws SecurityException to the method and take care of the caught exception further upstream. Furthermore, I would recommend using this library https://github.com/tbruyelle/RxPermissions if you interested in using reactivex methodology to deal with permissioning.

MegaChan
  • 350
  • 1
  • 2
  • 6
-2

Your targetSdkVersion is 23 or higher, just reduce it

Na Pro
  • 715
  • 1
  • 8
  • 23
  • You should properly handle permissions in newer versions of android – MichaelStoddart Oct 25 '16 at 09:42
  • 6.0 is not popular, we don't force to use api 23, at least for now. – Na Pro Oct 25 '16 at 10:13
  • According to android dashboards 18.7% of android devices are running marshmallow, you definitely should consider handling permissions on marshmallow and above, you risk losing a large portion of your user base because you deem it "not popular" – MichaelStoddart Oct 25 '16 at 10:40