This is because the getString method returns a nullable value (String?) but you are assigning it to something that takes a non-null value (expects String). If you want to fix it you could assign it to a default string if it is null like this
val villageId = getString("village_id") ?: "default"
This is due to your villageId can be null which you have got from getString("village_id")
for solving this you can use default value so when bundle don’t contains the provided key it will eventually returns the default value.
val villageId = getString("village_id", "My Default Value")
or you can use kotlin elvis to get other value when it’s null.
val villageId = getString("village_id") ?: "My Default Value"
or if you’re sure that intent will always contain the village id then you can use !!(not-null assertion operator) which will convert non-null value if not null else will throw exception
2
Answers
This is because the
getString
method returns a nullable value (String?
) but you are assigning it to something that takes a non-null value (expectsString
). If you want to fix it you could assign it to a default string if it is null like thisor to an empty string
This is due to your
villageId
can be null which you have got fromgetString("village_id")
for solving this you can use default value so when bundle don’t contains the provided key it will eventually returns the default value.
or you can use kotlin elvis to get other value when it’s null.
or if you’re sure that intent will always contain the village id then you can use !!(not-null assertion operator) which will convert non-null value if not null else will throw exception
you can more read about null safety in following link Null safety | Kotlin