简体   繁体   中英

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.

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. That is, it looks like details.get(0) == null .

A List details having many items can have first item a null object. before using that item check 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM