Logcat продолжает выдавать пустые ссылки на объекты при попытке настроить создание документа через firestore в процессе создания учетной записи, код приведен ниже, я новичок в java с моим университетским курсом, поэтому не знаете, как определить проблему.
Попытка получить информацию из полей edittext, сохраненных в коллекции firestore, если учетная запись успешно создана в auth, идентифицируемой идентификатором пользователя созданной учетной записи.
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)