简体   繁体   中英

How to fix a null object reference on document snapshot

I have an program where the MainActivity display the name and the email of the user on top of the screen by using document snapshot that been stored in firestore database

However it seems when I press the logout button it invoke this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.firestore.DocumentSnapshot.getString(java.lang.String)' on a null object reference

This is where the run tap points at this error:

DocumentReference docRef = mStore.collection("users").document(userID);
docRef.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
        name.setText(documentSnapshot.getString("Name"));
        email.setText(documentSnapshot.getString("email"));

    }
});

And this is the full MainActivity :

public class MainActivity extends BaseMainMenu {
    private static final String TAG = "TAG";
    private FirebaseAuth mfirebaseauth;
    private String motive[] = {"Once you learn to quit, it becomes a habit","Exercise is labor without weariness"
            ,"A feeble body weakens the mind","Get comfortable with being uncomfortable", "Confidence comes from discipline and training"
            , "Nothing will work unless you do", "All great achievements require time", "Pain is temporary. Quitting lasts forever"
            , "Don’t count the days, make the days count", "Action is the foundational key to all success"
            , "Once you are exercising regularly, the hardest thing is to stop it", "No pain, no gain" };
    TextView name, email, tv1;
    Button b1;


    FirebaseFirestore mStore;
    String userID;


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

        name = findViewById(R.id.nname);
        email = findViewById(R.id.eemail);

        mfirebaseauth = FirebaseAuth.getInstance();
        mStore = FirebaseFirestore.getInstance();
        userID = mfirebaseauth.getCurrentUser().getUid();

        Button logoutt =(Button) findViewById(R.id.btn_logout);
                logoutt.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        mfirebaseauth.signOut();
                        startActivity(new Intent(MainActivity.this, Login.class));
                        finish();
                    }
                });

        DocumentReference docRef = mStore.collection("users").document(userID);
        docRef.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                name.setText(documentSnapshot.getString("Name"));
                email.setText(documentSnapshot.getString("email"));

            }
        });

        Button i1 = (Button) findViewById(R.id.button4);
        i1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, homeorgym.class));
            }
        });

        Button i2 = (Button) findViewById(R.id.button6);
        i2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, Features.class));
            }
        });

        Button i3 = (Button) findViewById(R.id.button7);
        i3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, readProfileData.class));


            }
        });

        Button i4 = (Button) findViewById(R.id.button5);
        i4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, Meals.class));
            }
        });

        tv1 = (TextView) findViewById(R.id.txt_motive);
        b1 = (Button) findViewById(R.id.btn_motive);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Random random = new Random();
                int num = random.nextInt(motive.length);
                tv1.setText(motive[num]);    }
        });
    }
}

This is the screenshot of firestore firebase document

When you add a snapshot listener, you either get a DocumentSnapshot or you get a FirebaseFirestoreException in the onEvent callback. If you do get a FirebaseFirestoreException , you don't get a DocumentSnapshot , which is why you get a NullPointerException when you try to use that snapshot.

The solution is to first check whether there is an error, and only access the document once you've determine there is no error:

docRef.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
        if (e != null) {
            Log.w(TAG, "Listen failed.", e);
            return;
        }

        if (documentSnapshot != null && documentSnapshot.exists()) {
            name.setText(documentSnapshot.getString("Name"));
            email.setText(documentSnapshot.getString("email"));
        } else {
            Log.d(TAG, "Current data: null");
        }
    }
});

Once you log the error like this, you can also figure out what the root cause of the problem is and address that.

Also note that the code change I made is quite literally what the Firebase documentation on reading documents shows, so I recommend keeping that handy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM