0

I get this error when I Sign out .

Here is my error log

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
        at com.sp.schoolparkv2.MainActivity$1.onEvent(MainActivity.java:47)
        at com.sp.schoolparkv2.MainActivity$1.onEvent(MainActivity.java:44)

I already check both the XML and the firebase I cant seem to find a problem with it all the IDs are correct. Its able to sign in without a problem but when I signout it crashes but it still execute the signout procedure somehow.

here is a google drive link to the whole project https://drive.google.com/file/d/1GzTNP3yGzjBD1s5Q--NTRMbdcY_V2B_K/view?usp=sharing

Here is my code

  package com.sp.schoolparkv2;
    
    import androidx.annotation.Nullable;
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.firestore.DocumentReference;
    import com.google.firebase.firestore.DocumentSnapshot;
    import com.google.firebase.firestore.EventListener;
    import com.google.firebase.firestore.FirebaseFirestore;
    import com.google.firebase.firestore.FirebaseFirestoreException;
    import com.google.firebase.firestore.auth.User;
    
    public class MainActivity extends AppCompatActivity {
        Button mlogoutBtn;
        TextView name,age,gender,country,school;
        FirebaseAuth fAuth;
        FirebaseFirestore fStore;
        String UserID;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mlogoutBtn = findViewById(R.id.button);
            name = findViewById(R.id.Dname);
            age = findViewById(R.id.dage);
            gender = findViewById(R.id.Dgender);
            country = findViewById(R.id.DCountry);
            school = findViewById(R.id.DSchool);
    
            fAuth = FirebaseAuth.getInstance();
            fStore = FirebaseFirestore.getInstance();
    
            UserID = fAuth.getCurrentUser().getUid();
    
            DocumentReference documentReference = fStore.collection("users").document(UserID);
line 44     documentReference.addSnapshotListener(this, new EventListener <DocumentSnapshot>() {
                @Override
                public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
line 47             name.setText(documentSnapshot.getString("name"));
                    age.setText(documentSnapshot.getString("age"));
                    gender.setText(documentSnapshot.getString("gender"));
                    country.setText(documentSnapshot.getString("country"));
                    school.setText(documentSnapshot.getString("school"));
                }
            });

            mlogoutBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    FirebaseAuth.getInstance().signOut();
                    startActivity(new Intent(getApplicationContext(), Login.class));
                    finish();
                }
            });
    
        }
    }

XML File

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#9C27B0"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:layout_gravity="center_horizontal"
            android:src="@mipmap/ic_launcher" />

        <TextView
            android:id="@+id/Dname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="50dp"
            android:text="Your Name"
            android:textSize="24sp" />

        <TextView
            android:id="@+id/dage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:text="Your Age"
            android:textSize="24sp" />

        <TextView
            android:id="@+id/Dgender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:text="Your Gender"
            android:textSize="24sp" />

        <TextView
            android:id="@+id/DCountry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:text="Your Country"
            android:textSize="24sp" />

        <TextView
            android:id="@+id/DSchool"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:text="Your School"
            android:textSize="24sp" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="50dp"
            android:text="@string/logout" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
  • @Selvin: while that is good guidance in general, there's a bit more we can say here. I wrote up a quick answer below, and linked to the one you proposed as a duplicate from there too. – Frank van Puffelen Jan 23 '21 at 18:07
  • No, there is nothing peculiar in this question. Same old problem, he didn't check if something that can be null is null – Selvin Jan 23 '21 at 18:20

2 Answers2

3

Note that the onEvent method is called with two arguments:

public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
    name.setText(documentSnapshot.getString("name"));
    age.setText(documentSnapshot.getString("age"));
    gender.setText(documentSnapshot.getString("gender"));
    country.setText(documentSnapshot.getString("country"));
    school.setText(documentSnapshot.getString("school"));
}

You're completely ignoring the FirebaseFirestoreException, which explains the problem.

Most likely you require that the user is signed in, in order for them to be able to read the document. This means that once the user signs out, they lose their permission, and the database rejects the listener. This means your onEvent gets called again, this time with a FirebaseFirestoreException instead of a DocumentSnapshot.

So you should check the error, and only process the document when there was no error:

public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
  if (e != null) {
    name.setText(documentSnapshot.getString("name"));
    age.setText(documentSnapshot.getString("age"));
    gender.setText(documentSnapshot.getString("gender"));
    country.setText(documentSnapshot.getString("country"));
    school.setText(documentSnapshot.getString("school"));
  }
  else {
    Log.e("Firestore", "Error reading from Firestore", e);
  }
}

Troubleshooting NullPointerException almost always follows the same patter, so I recommend studying What is a NullPointerException, and how do I fix it? to learn how to figure something like this out on your own.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

I sovled my problem by doing this

userID = fAuth.getCurrentUser().getUid();
            final DocumentReference documentReference = fStore.collection("users").document(userID);
            documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
                @Override
                public void onEvent( DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
                    if (documentSnapshot != null && documentSnapshot.exists()) {
                        name.setText(documentSnapshot.getString("name"));
                        age.setText(documentSnapshot.getString("age"));
                        gender.setText(documentSnapshot.getString("gender"));
                        country.setText(documentSnapshot.getString("country"));
                        school.setText(documentSnapshot.getString("school"));

                    } else {
                        Log.d("tag", "onEvent: Document do not exists");
                    }
                    mlogoutBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            FirebaseAuth mAuth = FirebaseAuth.getInstance();
                            try {
                                mAuth.signOut();
                                Toast.makeText(MainActivity.this , "User Sign out!", Toast.LENGTH_SHORT).show();
                                
                            }catch (Exception e) {
                                Log.e(TAG, "onClick: Exception "+e.getMessage(),e );
                            }
                            startActivity(new Intent(getApplicationContext(),Login.class));
                            finish();
                        }
                    });
                }
            });