2

I got error message:

AddAddressActivity.kt: (69, 53): Type mismatch: inferred type is String? but String was expected

enter image description here

1
  • 7
    Please do not post pictures of code. Please paste edit your question and paste the actual text. Commented Jan 11, 2022 at 4:57

2 Answers 2

6

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"

or to an empty string

val villageId = getString("village_id").orEmpty()
Sign up to request clarification or add additional context in comments.

1 Comment

Or use the standard library function .orEmpty().
1

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

val villageId: String = getString("village_id")!!

you can more read about null safety in following link Null safety | Kotlin

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.