Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch: inferred type is FragmentActivity? but Context was expected when updating the support library to 27.0.0

Tags:

android

kotlin

I've updated my Kotlin project to use support library 27.0.0. When I try to get the Activity context in a Fragment I'm getting this error:

> Type mismatch: inferred type is FragmentActivity? but Context was expected
like image 640
Ivo Stoyanov Avatar asked Oct 31 '17 11:10

Ivo Stoyanov


1 Answers

It's safe to assume that activity or context is not null in any of the fragment's lifecycle methods (between onAttach and onDetach). In this case

context!!

seems better because if it's null when it's definitely NOT supposed to be null, something is terribly wrong and you should just crash.

In asynchronous callbacks of course check for null.

For me "!!" is never and option.

Then by all means abstract it away. This is what I did in my BaseFragment class:

val context: Context
    @JvmName("getContext2") 
    get() = getContext()!!

And then at use site:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    context // Context is *never* null here.
}

fun someCallbackMethod() {
    if (isAdded) {
        context // Context is also not null here.
    } else {
        // But it is null here.
    }
}

Unfounded null-checks everywhere are just as bad as the non-null assert operator.

This is equal to what would happen before support library 27 where nullability annotations were added. You could access context anywhere and it would crash if it were null and dereferenced.

Update: Recent support library introduced methods for this case:

  • requireActivity(): Activity
  • requireContext(): Context
  • requireHost(): Object
  • requireFragmentManager(): FragmentManager

The difference from my suggestion above is that these methods will throw IllegalStateException instead of KotlinNullPointerException.

like image 115
Eugen Pechanec Avatar answered Oct 16 '22 09:10

Eugen Pechanec