Reputation: 19514
bigPicture
is null sometimes. how to handle this?
App crash : java.util.NoSuchElementException: Key bigPicture is missing in the map.
data class NotificationModel(val version: String?,
val bigPicture: String?,
val title: String?,
val body: String?,
val messageData:String?,
val groupKey: String?) {
companion object {
fun from(map: Map<String?, String?>) = object {
val version by map
val bigPicture by map
val title by map
val body by map
val groupKey by map
val messageData by map
val data = NotificationModel(version, bigPicture, title, body,messageData, groupKey)
}.data
}
}
Upvotes: 0
Views: 1816
Reputation: 286
In Kotlin they provide two methods for getting value from a Map
myMap.get(key)
or mayMap[key]
: returns the value if it exists or returns null if it doesn'tmyMap.getValue(key)
: returns the value for the key or throws an NoSuchElementException
if the key does not exist.Upvotes: 2
Reputation: 15339
This kind of null check is what the Elvis operator
is for:
val bigPicture = map["bigPicture"] ?: ""
Upvotes: 1
Reputation: 1559
If key
is not present in the map
then only we get java.util.NoSuchElementException: Key bigPicture is missing in the map
. Look:
val map = mutableMapOf<String?,String?>()
map["version"] = "1.1"
//map["bigPicture"] = "my BigPic" // app crash because no key is present
map["bigPicture"] = null // No crash here as key is present but value is null
map["title"] = "My Title"
map["body"] = "My Body"
map["groupKey"] = "Group key"
map["messageData"] = "My Msg Data"
val notificationModel = NotificationModel.from(map)
Log.d("TAG==>>","BigPicture = ${notificationModel.bigPicture} ")
}
To avoid crash you may try below code:
data class NotificationModel(val version: String?,
val bigPicture: String?,
val title: String?,
val body: String?,
val messageData:String?,
val groupKey: String?) {
companion object {
fun from(map: MutableMap<String?, String?>) = object {
val version by map
val bigPicture = if (map.containsKey("bigPicture")) map["bigPicture"] else ""
val title by map
val body by map
val groupKey by map
val messageData by map
val data = NotificationModel(version, bigPicture, title, body,messageData, groupKey)
}.data
}
}
Upvotes: 1