rahmanarif710
rahmanarif710

Reputation: 61

intent.getStringExtra must not be null kotlin

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

Upvotes: 5

Views: 7469

Answers (4)

Ercan
Ercan

Reputation: 2821

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

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

Upvotes: 0

天枢破军
天枢破军

Reputation: 21

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")

Upvotes: 0

Sasi Kumar
Sasi Kumar

Reputation: 13358

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

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

Upvotes: 2

miensol
miensol

Reputation: 41678

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"

Upvotes: 8

Related Questions