Retrieve the default calendar id in Android

前端 未结 5 657
走了就别回头了
走了就别回头了 2021-01-04 02:51

I have the following code for adding event to calendar.

The problem is that I don\'t know how to retrieve the default calendar id.

l         


        
5条回答
  •  走了就别回头了
    2021-01-04 03:23

    This code worked for me

    private fun calendarId(): Long? {
        val uri = CalendarContract.Calendars.CONTENT_URI
        var cursor: Cursor?= null
    
        //Submit calendar query
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
            cursor = contentResolver?.query(uri, CALENDAR_PROJECTION, null, null, null)
    
        } else{
            ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.WRITE_CALENDAR), PERMISSION_REQUEST_WRITE_CALENDAR) }
    
         if (cursor != null) {
             Log.d("MainActivity", "Cursor is present")
             if(cursor.moveToFirst()) {
                 //Get required fields
                 val calID = cursor.getLong(CAL_ID)
                 val calName = cursor.getLong(CAL_NAME)
                 Log.d("MainActivity", "Calendar ID: $calID, Calendar Name: $calName")
                 cursor.close()
                 return calID
             }
         }
    
        //return null
        return null
    }
    

提交回复
热议问题