![](/img/trans.png)
[英]GSON fronJson : throwing error java.lang.NullPointerException: storage == null
[英]java.lang.NullPointerException: Gson().fromJson(placeJson, Place::class.java) must not be null
我在代码中使用了以下 function:
private fun sharedPreferences() = context.getSharedPreferences(
"sunny_weather",
Context.MODE_PRIVATE
)
fun getSavedPlace(): Place {
val placeJson = sharedPreferences().getString("place","")
return Gson().fromJson(placeJson, Place::class.java)
}
但出现以下错误
java.lang.NullPointerException: Gson().fromJson(placeJson, Place::class.java) must not be null
我发现了一个类似的问题,按照提问者的意思,虽然他的代码和我的不一样,他也写了getString function 但是第二个参数设置为null 所以他的程序出错了,改后他的程序运行良好. 但我把参数设置为“”,而不是null,但这是错误的。
使用“{}”作为默认值:
fun getSavedPlace(): Place { val placeJson = sharedPreferences().getString("place","{}") return Gson().fromJson(placeJson, Place::class.java) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.