Android app NullPointerException where it should not happen?

105
February 25, 2021, at 09:20 AM

I have an Android app that is recently published, and I'm receiving crash reports from Google Play Console. One of the crashes is strange. It happens in code similar to the following:

private final List<Item> items = new ArrayList<>();
public void addItem(Item item) {
    items.add(item);  // NullPointerException here!!
}

Apparently items is null when addItem is called, but it seems to me that it's impossible—I've initialized it at the declaration site. I can't imagine a situation in which this could happen, yet it happens a lot. Any idea?

Answer 1

Alright, psychic debugging time. The only way this could happen is if something is calling it as part of the object init, either during setup of other variables or an explicit init { ... } block.

You are almost certainly doing something like this elsewhere in the code:

import java.util.*;
class Main {
    private static class Item { }
    
    private final Item firstItem = setUpItemsAndReturnFirst();
    private final List<Item> items = new ArrayList<>();
    public void addItem(Item item) {
        items.add(item);  // NullPointerException here!!
    }
    
    private Item setUpItemsAndReturnFirst() {
        Item first = new Item();
        Item second = new Item();
        addItem(first);
        addItem(second);
        return first;
    }
    
    public static void main(String args[]) { 
        new Main();
    } 
}

This contains your sample code, and will crash on that line with a NullPointerException, because setUpItemsAndReturnFirst() is being called before items is initialized when it's used to initialize firstItem.

I assume it's behind some sort of conditional, in your case, since it presumably doesn't crash every time or you'd never have released it. But this is the general idea.

READ ALSO
How to pass parameters to Jenkins build using Jenkins Job Builder?

How to pass parameters to Jenkins build using Jenkins Job Builder?

I want to pass custom parameters to my Jenkins builds using Jenkins Job Builder

211
When I search a patient name that has another status while the &ldquo;pending&rdquo; checkbox is still checked I still get the search results for other status

When I search a patient name that has another status while the “pending” checkbox is still checked I still get the search results for other status

I have a table and the table has a column called statusBasically, this status can be in progress, pending or dispensed

116