-5

I'm new to android and firestore. I have built a small app and whenever I run my app, the app crashes at runtime eventhough the gradle build is successful. The following is the code for the main activity and Logcat for the better understanding.

package com.example.make;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.TextView;

import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nullable;

import io.opencensus.tags.Tag;

public class MainActivity extends AppCompatActivity {

private static final String Tag = "Firelog";

private List<Users> usersList;
private UsersListAdapter usersListAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RecyclerView mMainList = findViewById(R.id.main_list);

    usersList  = new ArrayList<>();
    usersListAdapter = new UsersListAdapter(usersList);
    mMainList.setLayoutManager(new LinearLayoutManager(MainActivity.this));
    mMainList.setAdapter(usersListAdapter);


    TextView mName = findViewById(R.id.item_name);
    TextView mStatus = findViewById(R.id.item_status);

    try {

        FirebaseFirestore db = FirebaseFirestore.getInstance();

        db.collection("Users").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {

                if (e != null) {

                    Log.d(Tag, "Error : " + e.getMessage(), new NullPointerException());


                    for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {

                        if (doc.getType() == DocumentChange.Type.ADDED) {

                            doc.getDocument().getReference().collection("Users").addSnapshotListener(new EventListener<QuerySnapshot>() {
                                @Override
                                public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                                    if (e != null) {
                                        Log.d("", "Error :" + e.getMessage(), new NullPointerException());
                                    }

                                    for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {

                                        if (doc.getType() == DocumentChange.Type.ADDED) {

                                            Log.d("USer Name :", doc.getDocument().getId());
                                        }
                                    }
                                }
                            });

                            Users users = doc.getDocument().toObject(Users.class);
                            usersList.add(users);
                            usersListAdapter.notifyDataSetChanged();

                        }

                    }
                }
            }
        });
    } catch (NullPointerException error) {
        mName.setText(error.getMessage());
    }
}

}

This is the error I get,

12-03 13:59:30.576 26036-26036/com.example.make E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.make, PID: 26036 java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.google.firebase.firestore.QuerySnapshot.getDocumentChanges()' on a null object reference at com.example.make.MainActivity$1.onEvent(MainActivity.java:65) at com.example.make.MainActivity$1.onEvent(MainActivity.java:56) at com.google.firebase.firestore.Query.lambda$addSnapshotListenerInternal$2(com.google.firebase:firebase-firestore@@17.1.3:885) at com.google.firebase.firestore.Query$$Lambda$3.onEvent(com.google.firebase:firebase-firestore@@17.1.3) at com.google.firebase.firestore.util.ExecutorEventListener.lambda$onEvent$0(com.google.firebase:firebase-firestore@@17.1.3:42) at com.google.firebase.firestore.util.ExecutorEventListener$$Lambda$1.run(com.google.firebase:firebase-firestore@@17.1.3) at android.os.Handler.handleCallback(Handler.java:754) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:163) at android.app.ActivityThread.main(ActivityThread.java:6383) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

I also put the try catch block to catch the nullpointer exception but it didn't work.Any help is appreciated. Thanks.

Krishi H
  • 526
  • 8
  • 26
  • 2
    QuerySnapshot object is null. check MainActivity.java on line 65 – shanwu Dec 03 '18 at 09:16
  • 2
    Possible duplicate of [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) – Vladyslav Matviienko Dec 03 '18 at 09:29

2 Answers2

3

The error states that :

java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.google.firebase.firestore.QuerySnapshot.getDocumentChanges()' on a null object reference

And inside your code:

for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {

The queryDocumentSnapshots object is null (as can be inferred by the annotation).

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
0
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
    if(queryDocumentSnapshots != null){
       for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
           if (doc.getType() == DocumentChange.Type.ADDED) {
              Log.d("USer Name :", doc.getDocument().getId());
           }
       }
    }
}

As the method clearly annotates, QuerySnapshot is nullable, so you have to add null check.

Mohammed Atif
  • 4,383
  • 7
  • 28
  • 57