Google are annotating many of the Android framework classes, to make them more Kotlin friendly.

Specifically, they're adding @Nullable and @NonNull annotations to function parameters, and return values.

This allows Kotlin to know whether a function returns a nullable type, such as Context?, rather than Context.


In our ContentProvider class (AppProvider), we only access the context when we know it can't be null.  However, the Java getContext method now returns Context? - which means Kotlin will assume that it can be null where we use it.


That results in errors in the code when we use Android 10, even though it compiled fine with Android Pie.

Type mismatch.
Required: Context
Found: Context?


You'll see errors in the query, insert, update and delete functions in AppProvider, whenever the context is used to get an instance of AppDatabase.

For example, in code like:

val db = AppDatabase.getInstance(context).readableDatabase


To fix the error, declare a local context variable at the start of the function

val context = requireContext(this)


For example, in the insert function:

override fun insert(uri: Uri, values: ContentValues?): Uri? {
    Log.d(TAG, "insert: called with uri $uri")
    val match = uriMatcher.match(uri)
    Log.d(TAG, "insert: match is $match")

    val recordId: Long
    val returnUri: Uri

    val context = requireContext(this)

    when (match) {


This solution will cause the app to crash with an exception, if the context is null.  But we know it can't be null at the places we're using it.  The app won't crash, because context can't be null.


Make sure you accept the import:

import androidx.core.content.ContentProviderCompat.requireContext


Watch out for those errors, in the next few videos, and use the solution above, to fix the error.

That also means that any safe-call operators on context become unnecessary.  You'll see suggestions from Android Studio, when context? can be replaced with context.