3

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

6
  • 1
    activity is calling your fragment's getActivity() which isn't guaranteed to not be null. So you'll have to do activity!!.applicationContext!! Commented Jan 21, 2019 at 19:58
  • im calling this method from my Fragment... i think when that fragment are created, my activity is not null. Right? Commented Jan 21, 2019 at 20:01
  • 1
    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 Commented Jan 21, 2019 at 20:08
  • You are right man. Im newbie on Kotlin, i started on a few days ago. Thx dude. Commented Jan 21, 2019 at 20:19
  • 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 nullability Commented Jan 21, 2019 at 20:23

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Is this the best we can do? Is there any other way to return a non null activity context? In my case I store the reference to a val in onCreate using activity!! then use that variable as my context reference.
Do like that and when activity will be null, you will have exception, as you said "There are scenarios in the life cycle of Android where the activity will be null during the instance of your Fragment" and then you call !! and get crash. Better way is use injection of context, or view context if available.
@AntonKogan injecting context is generally bad context. The nullability of context has been a part of the platform since it's existence and it's on the developer to use it correctly. Hence why requireActivity() requireApplication() requireContext() was brought in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.