Reputation: 61
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
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
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
Reputation: 41678
The problem is that you've declared values
variable as not nullable i.e. the compiler will:
null
or possibly null
valuesThe 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