首页 > 解决方案 > Firebase firestore 抛出空对象引用

问题描述

Logcat 在帐户创建过程中尝试通过 Firestore 创建文档时不断抛出空对象引用,代码如下,我是 Java 的新手,我的大学课程不知道如何识别问题。

如果帐户在 auth 中成功创建,则尝试将来自 edittext 字段的信息存储到 firestore 集合中,由创建帐户的用户 ID 标识。

public class CreateAccount extends AppCompatActivity implements 
View.OnClickListener {

private static final String TAG = "EmailPassword";
private EditText AccountEmail;
private EditText AccountPass;
private EditText AccountFirstname;
private EditText AccountSurname;
private EditText AccountTown;
private EditText AccountAge;
private FirebaseAuth mAuth;
public FirebaseFirestore cloudstorage;

@Override
//Code that executes when the activity begins; in this case simply setting the view.
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_account);
    AccountEmail = findViewById(R.id.textEditAccountEmail);
    AccountPass = findViewById(R.id.textEditAccountPass);
    AccountFirstname = findViewById(R.id.textEditAccountFirst);
    AccountSurname = findViewById(R.id.textEditAccountLast);
    AccountTown = findViewById(R.id.textEditAccountTown);
    AccountAge = findViewById(R.id.textEditAccountAge);
    mAuth = FirebaseAuth.getInstance();
    FirebaseFirestore cloudstorage = FirebaseFirestore.getInstance();
    //Auto signout for testing
    FirebaseAuth.getInstance().signOut();


}

public void createAccount(String email, String password) {
    Log.d(TAG, "createAccount:" + email);
    if (!Validate()) {
        return;
    }
    mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "createUserWithEmail:success");

                        databasecreate();

                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "createUserWithEmail:failure", task.getException());
                        Toast.makeText(CreateAccount.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }

                }
            });
}

public boolean Validate() {
    boolean valid = true;
    String email = AccountEmail.getText().toString();
    if (TextUtils.isEmpty(email)) {
        AccountEmail.setError("Required.");
        valid = false;
    } else {
        AccountEmail.setError(null);
    }
    String password = AccountPass.getText().toString();
    if (TextUtils.isEmpty(password)) {
        AccountPass.setError("Required.");
        valid = false;
    } else {
        AccountPass.setError(null);
    }
    return valid;
}

public void databasecreate() {
    FirebaseUser user = mAuth.getCurrentUser();
    String uid = user.getUid();

    Map<String, Object> userlist = new HashMap<>();
    userlist.put("email", AccountEmail.getText());
    userlist.put("password", AccountPass.getText());
    userlist.put("Forename", AccountFirstname.getText());
    userlist.put("Surname", AccountSurname.getText());
    userlist.put("Town", AccountTown.getText());
    userlist.put("Age", AccountAge.getText());
    userlist.put("UserID", uid);

    cloudstorage.collection("users").document(uid)
            .set(userlist)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d(TAG, "Document successfully written!");
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Error creating file", e);
                }
            });
}



@Override
public void onClick(View v) {
    int i = v.getId();
    if (i == R.id.btnCreate) {
        createAccount(AccountEmail.getText().toString(), AccountPass.getText().toString());
    }
}

public void onClickBack(View v) {
    Intent backIntent = new Intent(CreateAccount.this, Login.class);
    CreateAccount.this.startActivity(backIntent);
}
}

来自日志的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.coffeedrive.myquote, PID: 20895
    java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.firestore.CollectionReference com.google.firebase.firestore.FirebaseFirestore.collection(java.lang.String)' on a null object reference
        at com.example.adam.myquote.CreateAccount.databasecreate(CreateAccount.java:137)
        at com.example.adam.myquote.CreateAccount$1.onComplete(CreateAccount.java:92)
        at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


在函数中databasecreate(),您引用了类变量cloudstorage。这个变量永远不会被初始化,这就是你得到一个NPE. 在您的函数中,您正在函数范围内onCreate初始化一个不同的变量。只需更改行:cloudstorageonCreate

FirebaseFirestore cloudstorage = FirebaseFirestore.getInstance();

this.cloudstorage = FirebaseFirestore.getInstance();

或者干脆

cloudstorage = FirebaseFirestore.getInstance();

以便您初始化类变量。


推荐阅读