0

I'm a new to this and I have a project for my thesis, but I have some problems. I always get this error when I run my project, because of that my app always force close.

Attempt to invoke virtual method 'java.lang.Long com.google.firebase.firestore.QueryDocumentSnapshot.getLong(java.lang.String)' on a null object reference.

I don't know where the problem is, or maybe I wrote the wrong code.

public static void loadHome(MyCompleteListener completeListener){
    g_homeList.clear();

    g_firestore.collection("kuis").get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    Map<String, QueryDocumentSnapshot> docList = new ArrayMap<>();
                    for (QueryDocumentSnapshot doc : queryDocumentSnapshots){
                        docList.put(doc.getId(), doc);
                    }

                    QueryDocumentSnapshot homeListDoc = docList.get("jml_kuis");

                    long homeCount = homeListDoc.getLong("count");

                    for( int i=1; i <= homeCount; i++){
                        String docID = homeListDoc.getString("kuis" + String.valueOf(i) + "_id");
                        QueryDocumentSnapshot homeDoc = docList.get(docID);

                        int numOfTest = homeDoc.getLong("no_kuis").intValue();
                        String homeName = homeDoc.getString("name");
                        g_homeList.add(new HomeViewModel(docID, homeName, numOfTest));
                    }

                    completeListener.OnSuccess();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    completeListener.OnFailure();
                }
            });
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • If you want to read data from Firestore, I think that this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953) will help. – Alex Mamo Dec 27 '22 at 08:34

1 Answers1

0

Looks like some of your doc Ids are null. To fix this you might to check the data coming from firebase for the missing id.

To make the code run have add null checks like this:

 for(QueryDocumentSnapshot doc : queryDocumentSnapshots){
   if(doc.getId()!==null){
     docList.put(doc.getId(), doc);
   }
}
                    }
Ravi Mishra
  • 167
  • 1
  • 7