Firebase Firestore抛出空对象引用

时间:2018-12-21 16:36:55

标签: java android firebase google-cloud-firestore

在尝试通过帐户创建过程中的Firestore设置文档创建时,Logcat不断抛出空对象引用,代码如下,这是我大学课程中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)

1 个答案:

答案 0 :(得分:0)

在函数import tensorflow as tf import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten from tensorflow.keras.layers import Conv2D, MaxPooling2D DIR = '/home/.../' IMG_H = 256 IMG_W = 256 IMG_CH = 1 loadFile = DIR + 'Img.npz' X = np.load(loadFile) trainImgSet = X['trainImgSet'] trainLabelSet = X['trainLabelSet'] testImgSet = X['testImgSet'] print('Shape of trainImgSet: {}'.format(trainImgSet.shape)) print('Shape of trainLabelSet: {}'.format(trainLabelSet)) #print('Shape of testImgSet:{}'.format(testImgSet)) model = tf.keras.Sequential() model.add(tf.keras.layers.Conv2D(256, (3, 3), input_shape = (IMG_H, IMG_W, IMG_CH))) model.add(tf.keras.layers.Activation('relu')) model.add(tf.keras.layers.MaxPooling2D(pool_size=(1, 1))) model.add(tf.keras.layers.Conv2D(256, (3, 3))) model.add(tf.keras.layers.Activation('relu')) model.add(tf.keras.layers.MaxPooling2D(pool_size=(1, 1))) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(64)) model.add(tf.keras.layers.Dense(1)) model.add(tf.keras.layers.Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() #train the CNN model.fit(trainImgSet, trainLabelSet, batch_size=10, epochs=5, validation_split=0.1) Here is the error: Traceback (most recent call last): File "/home/Code/DeepCl.py", line 49, in <module> model.fit(trainImgSet, trainLabelSet, batch_size=10, epochs=5, validation_split=0.1) File "anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 1536, in fit validation_split=validation_split) File "/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 992, in _standardize_user_data class_weight, batch_size) File "/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 1169, in _standardize_weights training_utils.check_array_lengths(x, y, sample_weights) File "/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_utils.py", line 426, in check_array_lengths 'and ' + str(list(set_y)[0]) + ' target samples.') ValueError: Input arrays should have the same number of samples as target arrays. Found 166 input samples and 4 target samples. 中,您正在引用类变量databasecreate()。此变量从未初始化,这就是为什么您得到cloudstorage的原因。在NPE函数中,您正在onCreate函数范围内初始化另一个cloudstorage变量。只需更改行:

onCreate

FirebaseFirestore cloudstorage = FirebaseFirestore.getInstance();

或者简单地

this.cloudstorage = FirebaseFirestore.getInstance();

以便您初始化类变量。