intent.getStringExtra must not be null kotlin

Viewed 6903

I want to passing data with intent extra from fragment to activity, Usually I use anko common intent from activity to activity

startactivity<secondActivity>("values" to "123")

but in my case, I want to passing data from fragment to activity like this

activity?.startactivity<secondActivity>("values" to "123")

when I want to get String Extra in my activity,

val values: String = ""
val intent = intent
values = intent.getStringExtra("values")

I get Error

intent.getstringextra must not be null

Do you have a solution for my case? because I do that to get extra from activity to activity no problem

4 Answers

The problem is that you've declared values variable as not nullable i.e. the compiler will:

  • check that you yourself should not assign null or possibly null values
  • insert runtime checks whenever necessary to achieve safety

The Intent.getStringExtra may return null and thus the compiler is complaining.

You can declare the values variable as possibly null and handle that case in code e.g.:

val values: String? = intent.getStringExtra("values")
if(values == null){
   finish()
   return;
}

Or assign a default value in case the intent does not have values extra:

val values = intent.getStringExtra("values") ?: "Default values if not provided"

Use kotlin Null Safety. if its null it wont assign value

 var values: String = ""
 val intent = intent
 intent.getStringExtra("values")?.let {
   values=it
 }

Because you declare that values can't be null, if you want values can be null, you should declare it like this

var values:String? = null

Or if you want to get a default value when values are null, you can do something like this

values = if (intent.getStringExtra("values")==null) "" else intent.getStringExtra("values")

If you get data from a widget, make sure that you converted it to String.

val content: String = YourTextWidget.text.toString()

Related