3
votes

I need to get a Context from my activity. When i do that using:

   override fun getContext(): Context {

    return activity.applicationContext
}

i got:

safe ( .) or non-null asserted ( .) calls are allowed on a nullable receiver of type FragmentACtivity

1
activity is calling your fragment's getActivity() which isn't guaranteed to not be null. So you'll have to do activity!!.applicationContext!!ElliotM
im calling this method from my Fragment... i think when that fragment are created, my activity is not null. Right?Flávio Costa
There are scenarios in the life cycle of Android where the activity will be null during the instance of your Fragment. More often than not, activity will exist, but in this case Kotlin is forcing you to be smart about accessing it. A simple (but helpful) nuance of KotlinElliotM
You are right man. Im newbie on Kotlin, i started on a few days ago. Thx dude.Flávio Costa
No problem, a helpful approach to learning Kotlin in Android Studio is to click red errors (red squigglies under code) and use ALT+ENTER to get a solution to fix your problem - more often than not, it's Kotlin telling you to be hyper-conscious about nullabilityElliotM

1 Answers

2
votes

For formality purposes, posting answer here

activity is calling your fragment's getActivity() which isn't guaranteed to not be null. So you'll have to do activity!!.applicationContext!!

There are scenarios in the life cycle of Android where the activity will be null during the instance of your Fragment. More often than not, activity will exist, but in this case Kotlin is forcing you to be smart about accessing it. A simple (but helpful) nuance of Kotlin