0

I'm really new to programming in Android. I have the following error when I try to show a list after the update, delete or modify.

This is the error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.isc.dog, PID: 12520
    java.lang.NullPointerException: Parameter specified as non-null 
    is null: method 
    kotlin.jvm.internal.Intrinsics.checkNotNullParameter, 
    parameter it
   

I know it could be related to this piece of code below.

 fun getDoges() : MutableLiveData<List<Dog>> {
    val listaFinal = MutableLiveData<List<Dog>>()
    firestore
        .collection("dogesApp")
        .document(codigoUsuario)
        .collection("misDoges")
        .addSnapshotListener { instantanea, e ->  //Le toma una foto/recupera los lugares del usuario
            if (e != null) {
                Log.d("Firestore","Error recuperando Mascotas", e)
                return@addSnapshotListener
            }
            if (instantanea !=null) {  //Hay datos en la recuperación
                val lista = ArrayList<Dog>()
                val doges= instantanea.documents
                doges.forEach {

                    val dog = it.toObject(Dog::class.java)

                    if (dog != null) {  //Si se pudo convertir a un lugar
                        lista.add(dog)
                    }
                }
                listaFinal.value = lista
            }
        }
    return listaFinal
}

I don't know how to fix this exception.

SoftwareGuy
  • 1,121
  • 2
  • 11
  • 23
jamesdanil
  • 29
  • 3
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Tyler V Dec 16 '21 at 05:27
  • None of the answers to that question are really helpful to understanding how to resolve this Kotlin issue. That is a very Java-focused question. Even if someone knows what causes an NPE in Java, if they’re new to Kotlin, it can be surprising to see one because of its null-safety features. If that question weren’t locked I would say it’s fine and someone could add some Kotlin examples of ways NPEs can still happen in Kotlin when interacting with Java classes. – Tenfour04 Dec 16 '21 at 05:55

1 Answers1

0

If this is the code that is pointed to by the line number in the stack trace error, then the problem is that instantanea.documents must contain some null values, but you are assuming they are not null when you use it.toObject. You should change that to it?.toObject.

Also, this code isn’t going to accomplish anything because the Firestore API call is asynchronous. The outer function will return the empty listaFinal before the snapshot listener code is called, some time in the future. This issue is explained in the answers here.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154