[英]Why do I I get null point exception even though I safeguarded against it?
How do I safeguard against null points? 我如何防范零分? I tried this way:
我这样尝试:
var spr = context.getSharedPreferences("FAV", Context.MODE_PRIVATE)
var emptyArray: JsonArray = jsonArray()
var myjson = spr.getString("KEY", null)
//GET JSON FROM SHARED PREFERENCE
Log.d("TAG", "NOT NULL")
if(myjson != null) {
var parsedFavFromJson = Gson().fromJson<List<String>>(myjson)
//PARSE FROM JSON TO ARRAY
for (i in parsedFavFromJson) {
emptyArray.add(i)
Log.d("TAG", "" + i)
if (i == recipeArray!![counterX].recipeKey!!) {
Picasso.with(context)
.load(R.drawable.fav_icon_60at3x).into(favMarkerButton)
Log.d("TAG", "Match " + i)
} else {
Log.d("TAG", "WAS NULL")
Picasso.with(context)
.load(R.drawable.fav_unclicked_icon60at3x).into(favMarkerButton)
}
}
}
I have clearly stated the conditional if(myjson != null)
, still it pass through and crash with the error message java.lang.IllegalStateException: fromJson(json, typeToken<T>()) must not be null
. 我已经明确说明了条件
if(myjson != null)
,它仍然通过并崩溃并出现错误消息java.lang.IllegalStateException: fromJson(json, typeToken<T>()) must not be null
。 There is no clear indication where the error actually occur - it actually points to an empty code line! 没有明确指示错误实际上在哪里发生的-它实际上指向空的代码行! If I remove the code above, things are working fine.
如果删除上面的代码,一切正常。 I also tried using:
我也尝试使用:
var myjson = spr.getString("KEY", null).let {
...and so on, with the same result. ...等等,结果相同。 Am I missing something here?
我在这里想念什么吗?
UPDATE I checked variable myjson
and it is clearly null
. UPDATE我检查变量
myjson
,它显然是 null
。 Question is why the conditional if(myjson != null)
passed... 问题是为什么条件
if(myjson != null)
通过...
In short, you're missing the question mark. 简而言之,您错过了问号。
You expect that in block: 您期望在块中:
spr.getString("KEY", null).let { it }
Won't be null? 不会为空吗? That's incorrect.
不对
Correct syntax is 正确的语法是
spr.getString("KEY", null)?.let { it }
Easy to miss. 容易错过。
Same goes for working with nested JSONs. 使用嵌套JSON也是如此。 You should never use bang-bang (
!!
) in Kotlin. 您永远不要在Kotlin中使用bang-bang(
!!
)。 Use the safe syntax instead: 请改用安全语法:
recipeArray?[counterX].recipeKey
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.