[英]Why does a non-empty List throw a Null Pointer Exception?
I have an List array 'details'. 我有一个列表数组“细节”。
List<HistoryDetails> details
where HistoryDetails is an object containing strings. 其中HistoryDetails是包含字符串的对象。
When I check the size it gives me a positive value. 当我检查尺寸时,会给我一个正值。
details.size()
But when I try to access an element it throws a null pointer exception. 但是,当我尝试访问元素时,它将引发空指针异常。
details.get(0).getFirstElement();
Attempt to invoke virtual method 'java.lang.String com.HistoryDetails.getFirstElement()' on a null object reference
I am invoking the element at the very next line to where I check the size. 我正在检查尺寸的下一行调用元素。 Hence, nothing should be reset.
因此,不应重置任何内容。 What could be wrong?
有什么事吗
It looks like details
is a List
, but the first element of the List
is null. 它看起来像
details
是一个List
,但的第一个元素List
为空。 That is, it looks like details.get(0) == null
. 也就是说,它看起来像
details.get(0) == null
。
A List details
having many items can have first item a null object. 具有许多项目的列表
details
可以使第一个项目为空对象。 before using that item check null. 使用该项目之前,请检查null。
if(details.get(0)!=null){
details.get(0).getFirstElement();
}
因为它包含null。
Log.d("TEST", details.get(0)); //should return null
This will avoid the null pointer exception: 这将避免空指针异常:
if (!details.isEmpty()) {
details.get(0).getFirstElement();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.