I'm totally new to Firebase and need to know how to check if my writing task was successful because if I don't, the MainActivity
starts and messes up my Register
progress.
This checks if Username
is already taken and registers the user if it isn't:
Query usernamequery = myRef.orderByChild("Username").equalTo(Username);
usernamequery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// TODO: handle the case where the data already exists
editText.setError("Username taken!");
return;
}
else {
// TODO: handle the case where the data does not yet exist
myRef.child("Users").child(Username).child("Userid").setValue(user.getUid());
myRef.child("Users").child(Username).child("Username").setValue(Username);
startActivity(maps);
finish();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Username.this, "Error", Toast.LENGTH_LONG).show();
}
});
But I want the Intent to Main Activity (maps) only be fired when
myRef.child("Users").child(Username).child("Userid").setValue(user.getUid());
and the other one is finished with its task and is successful.
What can I do?
To know when a write operation has completed on the server, add a completion listener:
myRef.child("Users").child(Username).child("Userid").setValue(user.getUid(), new DatabaseReference.CompletionListener() {
void onComplete(DatabaseError error, DatabaseReference ref) {
System.err.println("Value was set. Error = "+error);
// Or: throw error.toException();
}
});
If there was an error, details will be in the error
operation. If the write operation was completed without problems, the error
will be null
.
If you want to write to multiple locations with a single operation, you'll want to look at the update()
method
The correct overload for setValue()
is documented here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With