Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 758
rahmanarif710 Avatar asked Sep 20 '18 03:09

rahmanarif710


Video Answer


2 Answers

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

 var values: String = ""
 val intent = intent
 intent.getStringExtra("values")?.let {
   values=it
 }
like image 26
sasikumar Avatar answered Nov 15 '22 07:11

sasikumar


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"
like image 152
miensol Avatar answered Nov 15 '22 07:11

miensol