每当我退出时应用程序就会崩溃

时间:2021-01-23 17:40:06

标签: java android firebase android-layout google-cloud-firestore

退出时出现此错误。

这是我的错误日志

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)

我已经检查了 XML 和 firebase 我似乎找不到问题,所有 ID 都是正确的。它能够毫无问题地登录,但是当我退出时它崩溃了,但它仍然以某种方式执行退出过程。

这里是整个项目的 Google Drive 链接 https://drive.google.com/file/d/1GzTNP3yGzjBD1s5Q--NTRMbdcY_V2B_K/view?usp=sharing

这是我的代码

  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 文件

<?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>

2 个答案:

答案 0 :(得分:3)

请注意,调用 onEvent 方法时带有两个参数:

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"));
}

您完全忽略了解释问题的 FirebaseFirestoreException

您很可能要求用户登录,以便他们能够阅读文档。这意味着一旦用户退出,他们将失去他们的权限,并且数据库拒绝监听器。这意味着您的 onEvent 再次被调用,这次使用的是 FirebaseFirestoreException 而不是 DocumentSnapshot

所以你应该检查错误,只有在没有错误时才处理文档:

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);
  }
}

NullPointerException 进行故障排除几乎总是遵循相同的模式,因此我建议您学习 What is a NullPointerException, and how do I fix it? 以了解如何自行解决此类问题。

答案 1 :(得分:0)

我通过这样做解决了我的问题

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();
                        }
                    });
                }
            });