Retrieve the default calendar id in Android

前端 未结 5 679
走了就别回头了
走了就别回头了 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:22

    I used following code to get the calendar ID.

    private fun getCalendarId(context: Context) : Long? {
        val projection = arrayOf(Calendars._ID, Calendars.CALENDAR_DISPLAY_NAME)
    
        var calCursor = context.contentResolver.query(
            Calendars.CONTENT_URI,
            projection,
            Calendars.VISIBLE + " = 1 AND " + Calendars.IS_PRIMARY + "=1",
            null,
            Calendars._ID + " ASC"
        )
    
        if (calCursor != null && calCursor.count <= 0) {
            calCursor = context.contentResolver.query(
                Calendars.CONTENT_URI,
                projection,
                Calendars.VISIBLE + " = 1",
                null,
                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)
    
                Log.d("Calendar name = $calName Calendar ID = $calID")
    
                calCursor.close()
                return calID.toLong()
            }
        }
        return null
    }
    

    So do not pass 0, 1 or 3 as Calendar ID. Use above function instead.

    Also, check if Calendar ID is null and do not perform operations with it if it is null.

            val calendarId = getCalendarId(context)
            if (calendarId != null) {
            //Call operations e.g.: Insert operation
            }
    

提交回复
热议问题