1

please help the load categories method is showing this exception I am trying to fetch data from firebase and this null pointer exception is coming up somebody told me that he solved this problem using typecasting like he did type conversion to parse the value to int. I don't know how it will happen. Help please the code is

public class dbquery  {

public static FirebaseFirestore g_firestore;
public static List<testcategorymodel> g_catList = new ArrayList<>();
public static int g_selected_cat_index = 0;
public static List<TestModel> g_testlist = new ArrayList<>();
public static int g_selected_test_index = 0;
public static List<QuestionModel> g_quesList = new ArrayList<>();
public static ProfileModel myProfile = new ProfileModel("NA",null);


public static void createUserData(String email, String name,final mycompletelistener completelistener) {
   try {


       Map<String, Object> userData = new ArrayMap<>();
       userData.put("EMAIL_ID", email);
       userData.put("NAME", name);
       userData.put("TOTAL_SCORE", 0);

       DocumentReference userDoc = g_firestore.collection("USERS").document(FirebaseAuth.getInstance().getCurrentUser().getUid());

       WriteBatch batch = g_firestore.batch();

       batch.set(userDoc, userData);

       DocumentReference countDoc = g_firestore.collection("USERS").document("TOTAL_USERS");
       batch.update(countDoc, "COUNT", FieldValue.increment(1));

       batch.commit()
               .addOnSuccessListener(new OnSuccessListener<Void>() {
                   @Override
                   public void onSuccess(Void unused) {
                       completelistener.onSuccess();
                   }
               })
               .addOnFailureListener(new OnFailureListener() {
                   @Override
                   public void onFailure(@NonNull Exception e) {
                       completelistener.onFailure();
                   }
               });

   }catch (Exception e)
   {        e.printStackTrace();
       Log.d("myApp", "error" + e);
   }
}

public static void getUserData(final mycompletelistener completelistener)
{try {
    g_firestore.collection("USERS").document(FirebaseAuth.getInstance().getUid())
            .get()
            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                @Override
                public void onSuccess(DocumentSnapshot documentSnapshot) {
                    myProfile.setName(documentSnapshot.getString("NAME"));
                    myProfile.setEmail(documentSnapshot.getString("EMAIL_ID"));
                    completelistener.onSuccess();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    completelistener.onFailure();
                }
            });
    }catch (Exception e1)
        { e1.printStackTrace();
            Log.d("myApp", "getUserData: " + e1);
        }
}

public static void loadcategories(final mycompletelistener completelistener) {

   try {
       g_catList.clear();
       g_firestore.collection("EXAM").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 catListDooc = docList.get("Categories");

                       long catCount = catListDooc.getLong("COUNT");

                       for (int i = 1; i <= catCount; i++) {
                           String catID = catListDooc.getString("CAT" + String.valueOf(i) + "_ID");
                           QueryDocumentSnapshot catDoc = docList.get(catID);
                           int noOfTest = catDoc.getLong("NO_OF_TESTS").intValue();
                           String catName = catDoc.getString("NAME");
                           g_catList.add(new testcategorymodel(catID, catName, noOfTest));

                       }

                       completelistener.onSuccess();


                   }
               })
               .addOnFailureListener(new OnFailureListener() {
                   @Override
                   public void onFailure(@NonNull Exception e) {
                       completelistener.onFailure();
                   }
               });
   }catch (Exception e2){
       e2.printStackTrace();
       Log.d("myApp", "loadcategories: " + e2);
   }
}

public static void loadTestData(final mycompletelistener completelistener){

    try {
        g_testlist.clear();
        g_firestore.collection("EXAM").document(g_catList.get(g_selected_cat_index).getDocID())
                .collection("TESTS_LIST").document("TESTS_INFO")
                .get()
                .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                    @Override
                    public void onSuccess(DocumentSnapshot documentSnapshot) {

                        int noOfTests = g_catList.get(g_selected_cat_index).getNoOfTests();

                        for (int i = 1; i <= noOfTests; i++) {
                            g_testlist.add(new TestModel(
                                    documentSnapshot.getString("TEST" + String.valueOf(i) + "_ID"),
                                    0,
                                    documentSnapshot.getLong("TEST" + String.valueOf(i) + "_TIME").intValue()

                            ));

                        }


                        completelistener.onSuccess();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        completelistener.onFailure();
                    }
                });
    }catch (Exception e3)
    {
        e3.printStackTrace();
        Log.d("myapp", "loadTestData: " + e3);
    }
}

public static void loadquestions(mycompletelistener completelistener)
{
    try {
        g_quesList.clear();
        g_firestore.collection("Questions")
                // .whereEqualTo("CATEGORY", g_catList.get(g_selected_cat_index).getDocID())
                .whereEqualTo("TEST", g_testlist.get(g_selected_test_index).getTestID())
                .get()
                .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        // Log.d("myApp","checking 01: "+g_catList.get(g_selected_cat_index).getDocID());
                        //Log.d("myApp","checking 02: "+g_testlist.get(g_selected_test_index).getTestID());
                        for (DocumentSnapshot doc : queryDocumentSnapshots) {

                            g_quesList.add(new QuestionModel(
                                    doc.getString("QUESTION"),
                                    doc.getString("A"),
                                    doc.getString("B"),
                                    doc.getString("C"),
                                    doc.getString("D"),
                                    doc.getLong("ANSWER").intValue()
                            ));
                        }
                        // Log.d("g_quesList", Arrays.toString(g_quesList.toArray()));
                        completelistener.onSuccess();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        completelistener.onFailure();
                    }
                });
    }catch (Exception e4)
    {
        e4.printStackTrace();
        Log.d("myAPP", "loadquestions: " + e4);
    }
}
public static void loadData(final mycompletelistener completelistener)
{  try {
    loadcategories(new mycompletelistener() {
        @Override
        public void onSuccess() {
            getUserData(completelistener);
        }

        @Override
        public void onFailure() {
            completelistener.onFailure();
        }
    });
}catch (Exception e5)
{
    e5.printStackTrace();
    Log.d("myApp", "loadData: " + e5);
}
}
}

Here in the load categories method exception is coming the exception is like this it clearly shows that the exception error are at 119 and 102 which are in the load categories they are 119 int noOfTest = catDoc.getLong("NO_OF_TESTS").intValue(); 102 addOnSuccessListener(new OnSuccessListener()

022-05-17 15:55:06.453 10701-10701/com.example.exam E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.exam, PID: 10701
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Long com.google.firebase.firestore.QueryDocumentSnapshot.getLong(java.lang.String)' on a null object reference
    at com.example.exam.dbquery$6.onSuccess(dbquery.java:119)
    at com.example.exam.dbquery$6.onSuccess(dbquery.java:102)
    at com.google.android.gms.tasks.zzm.run(com.google.android.gms:play-services-tasks@@18.0.1:1)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:236)
    at android.app.ActivityThread.main(ActivityThread.java:7864)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)

These screenshots have the firebase firestore structure

category 1

categoery 2

Test data

every category is structured the same like shown in picture above

Questions data

The model for g_catList is this

package com.example.exam;

public class testcategorymodel {

private String docID;
private String name;
private int noOfTests;

public testcategorymodel(String docID, String name, int noOfTests) {
    this.docID = docID;
    this.name = name;
    this.noOfTests = noOfTests;
}

public String getDocID() {
    return docID;
}

public void setDocID(String docID) {
    this.docID = docID;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getNoOfTests() {
    return noOfTests;
}

public void setNoOfTests(int noOfTests) {
    this.noOfTests = noOfTests;
}
}
 

please help

  • Please edit your question and add your database structure as a screenshot. – Alex Mamo May 17 '22 at 10:54
  • This returns `null`: `QueryDocumentSnapshot catDoc = docList.get(catID)`, likely because `catID` doesn't exist. I'd check: `if (catDoc != null) { ... }` – Martin Zeitler May 17 '22 at 11:05
  • I tried putting int after QueryDocumentSnapshot catDoc = docList.get(catID) statement but it shows the same exception which i think means it is getting inside the if and passing error at int noOfTest = catDoc.getLong("NO_OF_TESTS").intValue(); – 068_tushar chand May 17 '22 at 11:27
  • This code was working when i first tried it, But when i stored more data in firebase this error came – 068_tushar chand May 17 '22 at 14:49
  • somebody told me that he solved this problem using typecasting like he did type conversion to parse the value to int. I don't know how it will happen. Help please – 068_tushar chand May 18 '22 at 02:32
  • can you check this [link](https://stackoverflow.com/questions/62420975/attempt-to-invoke-virtual-method-java-lang-long-com-google-firebase-firestore-d) which might help. – Sathi Aiswarya May 18 '22 at 07:28

0 Answers0