Can someone help me understand how a NullPointerEx...
# android
n
Can someone help me understand how a NullPointerException (NPE) can occur in the following scenario? I'm using a singleton class instantiated with DI, and I'm encountering an NPE when calling
items.find
. The exception message is:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.models.Item.getId()' on a null object reference.
How could this be happening?
Copy code
class ItemRepositoryImpl : ItemRepository {
    private val items = mutableListOf<Item>()

    private fun processItem(inputItem: InputItem?, subject: BehaviorSubject<ItemState>) {
        if (inputItem != null) {
            items.find { it.id == inputItem.itemId }?.let {
                it.markAsProcessed()
                it.isActive = true
            }
            subject.onNext(ItemState.ShowItem(inputItem))
        } else {
            subject.onNext(ItemState.Empty)
        }
    }
}
How could this be causing an NPE when
items.find
is called?
m
It that the whole class, because nothing ever populates
items
.If there is more happening, could be issues where another thread is getting access to
ItemRepositoryImpl
before it is fully constructed. Could be that something is casting
items
to something that allows inserting a
null
into it. Another thought is that intrinsics are complaining that
Item.id
is null because something like a serializer deserialized a null into it.
d
How is the list being populated?
n
In this case, the list is only being populated once at initiation. BUT, even if the list of items were empty, it doesn't explain the crash since it has started iterating over the cards. Thats atleast what I am thinking
b
is id mapped with your model id?