• 10
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Problem to get Context in FragmentView Kotlin

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
    • im calling this method from my Fragment... i think when that fragment are created, my activity is not null. Right?
      • 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
    • 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
      • 2
    • activity is calling your fragment's getActivity() which isn't guaranteed to not be null. So you'll have to do activity!!.applicationContext!!

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

  • 1
Reply Report
    • 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.