Logcat keeps throwing null object references while attempting to setup a document creation through firestore in an account creation process, code is below, im new to java with my university course so are unsure how to identify the problem.
Attempting to have information from the edittext fields stored into the firestore collection if the account is successfully created in auth, identified by the user ID of the created account.
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);
}
}
Error from log:
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)
In the function databasecreate()
you're referencing the class variable cloudstorage
. This variable is never initialized and is why you're getting an NPE
. In your onCreate
function you're initializing a different cloudstorage
variable within the scope of the onCreate
function. Simply change the line:
FirebaseFirestore cloudstorage = FirebaseFirestore.getInstance();
to
this.cloudstorage = FirebaseFirestore.getInstance();
or simply
cloudstorage = FirebaseFirestore.getInstance();
so that you initialize the class variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.