Search code examples
javaandroidnullpointerexceptioncrash

Android app NullPointerException where it should not happen?


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?


Solution

  • 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.