'Calendar ID returns null - can fetch for Android 12 version

I am working in adding calendar event in background action , so as the calendar Id differs based on device I used a solution from stack overflow for fetching the calendar ID . It works for all version below 12 . In Android 12 the fetching of calendar ID returns null . Is there any update for Android version 12 .Thanks in advance

The working code snippet for fetching the calendar Id below android version 12

private fun getCalendarId(context: Context) : Long? { val projection = arrayOf(CalendarContract.Calendars._ID, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME)

var calCursor = context.contentResolver.query(
    CalendarContract.Calendars.CONTENT_URI,
    projection,
    CalendarContract.Calendars.VISIBLE + " = 1 AND " + CalendarContract.Calendars.IS_PRIMARY + "=1",
    null,
    CalendarContract.Calendars._ID + " ASC"
)

if (calCursor != null && calCursor.count >= 0) {
    calCursor = context.contentResolver.query(
        CalendarContract.Calendars.CONTENT_URI,
        projection,
        CalendarContract.Calendars.VISIBLE + " = 1",
        null,
        CalendarContract.Calendars._ID + " ASC"
    )
}

if (calCursor != null) {
    if (calCursor.moveToFirst()) {
        val calName: String
        val calID: String
        val nameCol = calCursor.getColumnIndex(projection[1])
        val idCol = calCursor.getColumnIndex(projection[0])

        calName = calCursor.getString(nameCol)
        calID = calCursor.getString(idCol)

        calCursor.close()
        return calID.toLong()
    }
}
return null

}

I tried to fetch the calendar ID for android version 12 . Need to get the calendar ID for Version 12



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source