I'm not sure what the problem is. I'm a beginner developer and I coded a registration/login page for an Android app I'm working on. New users are saved in Firebase Authorization but not in Firebase Database. My current rules are set to false but when I try to set them to true, the app keeps returning to the SetupActivity rather than the MainActivity. The app works fine when the rules are set to false but as I said, nothing appears in the Database. Here is my code:
public class SetupActivity extends AppCompatActivity {
private EditText FullName, EmailAddress, Password, CountryName;
private Button SaveInfoButton;
private ProgressDialog LoadingBar;
private CircleImageView ProfileImage;
private FirebaseAuth register_auth;
private DatabaseReference userreference;
private String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
register_auth = FirebaseAuth.getInstance();
currentUserID = register_auth.getCurrentUser().getUid();
userreference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
FullName = findViewById(R.id.name_setup);
EmailAddress = findViewById(R.id.email_setup);
Password = findViewById(R.id.password_setup);
CountryName = findViewById(R.id.country_setup);
SaveInfoButton = findViewById(R.id.save_button);
ProfileImage = findViewById(R.id.profile_setup);
LoadingBar = new ProgressDialog(this);
SaveInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
String full_name = FullName.getText().toString();
String email = EmailAddress.getText().toString();
String password = Password.getText().toString();
String country = CountryName.getText().toString();
if(TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(full_name)) {
Toast.makeText(this, "Please enter your name.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(country)) {
Toast.makeText(this, "Please enter country.", Toast.LENGTH_SHORT).show();
}
else {
LoadingBar.setTitle("Creating new account!");
LoadingBar.setMessage("Please wait while your account is being created.");
LoadingBar.show();
LoadingBar.setCanceledOnTouchOutside(true);
register_auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
LoadingBar.dismiss();
Toast.makeText(SetupActivity.this, "Registration was successful!", Toast.LENGTH_SHORT).show();
SaveAccountInformation();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Registration unsuccessful." + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
}
private void SaveAccountInformation() {
String full_name = FullName.getText().toString();
String country = CountryName.getText().toString();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("fullname", full_name);
childUpdates.put("country", country);
childUpdates.put("status", "Hey there, I am using Study Guide!");
childUpdates.put("birthday", "none");
userreference.updateChildren(childUpdates).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendToLogin();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "An error occurred. " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
private void SendToLogin() {
Intent LoginIntent = new Intent(SetupActivity.this,LoginActivity.class);
LoginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(LoginIntent);
finish();
}
}
If someone could point me in the right direction or let me know what I'm doing wrong, it will be very much appreciated!
Hazal you are not saving the data , you are updating the data so change your code
from
userreference.updateChildren(childUpdates)
To
userreference.setValue(childUpdates)
You need to manually save the users in your Firebase Database once a new user is registered.
You can look at the docs on how to write data.
Related
I'm trying to create a chat app and I have to register users and I'm doing it with Firebase. Once I have entered all the data I click on register and I get the message:
You can't register with this email or password
Then it doesn't go successful.
I don't think there is anything wrong with the code. I have the emulator connected to the internet, I have connected firebase to the app, I don't know if I should check other things.
I imported this project from github. Maybe I did something wrong in the process? Can you explain what I could have done wrong?
Error in Log:
E/Auth: Unable to create user
com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The email address is badly formatted.
at com.google.android.gms.internal.firebase-auth api.zzti.zza(com.google.firebase:firebase-auth##21.0.3:28)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Register");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
username = findViewById(R.id.username);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_register = findViewById(R.id.btn_register);
firebaseAuth = FirebaseAuth.getInstance();
// When register is clicked check if fields are empty and if password is longer than 6 characters and call register method
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_username = username.getText().toString();
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
if (TextUtils.isEmpty(txt_username) || TextUtils.isEmpty(txt_email) || TextUtils.isEmpty(txt_password)) {
Toast.makeText(RegisterActivity.this, "All fields are required", Toast.LENGTH_SHORT).show();
}
else if (txt_password.length() < 6) {
Toast.makeText(RegisterActivity.this, "Password must be at least 6 characters", Toast.LENGTH_SHORT).show();
}
else {
register(txt_username, txt_email, txt_password);
}
}
});
}
private void register(final String username, final String email, final String password) {
// If register task is successful add a reference to Users
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id", userid);
hashMap.put("username", username);
hashMap.put("imageURL", "default");
hashMap.put("status", "offline");
hashMap.put("search", username.toLowerCase());
reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
}
else {
Toast.makeText(RegisterActivity.this, "You can't register with this email or password", Toast.LENGTH_SHORT).show();
}
}
});
}
When a task fails, it contains an exception with details about the cause of the problem. You should log that exception, so that you can find and fix the root cause:
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
...
}
else {
Log.e("Auth", "Unable to create user", task.getException()); // 👈
Toast.makeText(RegisterActivity.this, "You can't register with this email or password", Toast.LENGTH_SHORT).show();
}
}
I am working on a project which required firebase utilities so I did all those things required but my authentication is not taking place and thereby my data is not being uploaded in the firestore. I have tried many things and found that during the time of execution my onComplete listener is calling failure and thus a toast is popped authentication failure so I think the main problem lies in the onComplete listener but I couldn't fix it. My code is as follows-
*
private TextView username;
private TextView password;
private AutoCompleteTextView email;
private ProgressBar progress_bar;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username_account);
password = findViewById(R.id.password_account);
email = findViewById(R.id.email_account);
Button create_account = findViewById(R.id.create_acct_button);
progress_bar = findViewById(R.id.create_acct_progress);
firebaseAuth = FirebaseAuth.getInstance();
create_account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(email.getText().toString())
&& !TextUtils.isEmpty(password.getText().toString())
&& !TextUtils.isEmpty(username.getText().toString())) {
String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
String Username = username.getText().toString().trim();
createUserEmailAccount(Email, Password, Username);
} else {
Toast.makeText(CreateAccountActivity.this,
"Empty Fields Not Allowed",
Toast.LENGTH_LONG)
.show();
}
}
});
}
private void createUserEmailAccount(String email, String password, final String username) {
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(username)) {
progress_bar.setVisibility((View.VISIBLE));
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener( CreateAccountActivity.this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete( #NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Map<String, Object> userobj = new HashMap<>();
userobj.put("userId", "currentuserId");
userobj.put("username", username);
db.collection("journal")
.add(userobj)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot successfully written!");
progress_bar.setVisibility(View.INVISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
} else {
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(CreateAccountActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
progress_bar.setVisibility(View.INVISIBLE);
}
}
});
}
}
}*
I am trying to sync my Realtime Firebase database with my code.
I currently have Firebase Auth working, and I am able to get user ids, but my Realtime database stays on null. My Firebase Realtime database rules are currently set to true.
Is there something wrong with my code? I am trying to pull in the user id, first name, and last name into the Firebase Database.
public class Add_Info_After_Registration extends AppCompatActivity {
private EditText FirstName, LastName;
private ImageButton RegisterInfoButton;
private FirebaseAuth mAuth;
private DatabaseReference UsersReference;
//Firebase Things//
String currentUserID;
//Firebase Things//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__info__after__registration);
//this is referring to storing username information in firebase//
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersReference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
//this is referring to storing username information in firebase//
FirstName = (EditText) findViewById(R.id.add_info_first_name);
LastName = (EditText) findViewById(R.id.add_info_last_name);
RegisterInfoButton = (ImageButton) findViewById(R.id.register_submit_button);
mAuth = FirebaseAuth.getInstance();
RegisterInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SaveAccountSetUpInformation();
SendUserToMainActivity();
}
});
}
private void SaveAccountSetUpInformation()
{
String firstname = FirstName.getText().toString();
String lastname = LastName.getText().toString();
if(TextUtils.isEmpty(firstname))
{
Toast.makeText(this, "Please insert first name", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(lastname))
{
Toast.makeText(this, "Please insert last name", Toast.LENGTH_SHORT).show();
}
else
{
HashMap userMap = new HashMap();
userMap.put("firstname", firstname);
userMap.put("lastname", lastname);
//this is referring to storing username information in firebase//
UsersReference.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(Add_Info_After_Registration.this, "Your Account is Created Sucessfully", Toast.LENGTH_LONG).show();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(Add_Info_After_Registration.this, "Error Occured:"+ message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void SendUserToMainActivity()
{
Intent setupIntent = new Intent(Add_Info_After_Registration.this, MainActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
}
I'm making social media app that has user profile. I want to save their profile data after they have done their registration. Although the registration is successful, but the user's email and password are not saving in the Firebase database. I've also checked the rules, I use test mode.
Here's my rule:
{
"rules": {
".read": true,
".write": true
}
}
Here's my codes:
public class SignUpActivity extends AppCompatActivity
{
private Button btn_signin,btn_signup;
private EditText inputEmail, inputPassword, inputconPassword;
private ProgressBar progressBar;
private FirebaseAuth auth;
private FirebaseUser firebaseuser;
private static final String PASSWORD_PATTERN ="((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";
private static final String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
auth = FirebaseAuth.getInstance();
btn_signin = (Button) findViewById(R.id.btn_signin);
btn_signup = (Button) findViewById(R.id.btn_signup);
inputEmail = (EditText) findViewById(R.id.u_email);
inputPassword = (EditText) findViewById(R.id.u_password);
inputconPassword = (EditText) findViewById(R.id.u_conpassword);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btn_signin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
}
});
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = inputEmail.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (!validateForm())
{
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful())
{
Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignUpActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
firebaseuser = auth.getCurrentUser();
User myUserInsertObj = new User(inputEmail.getText().toString().trim(),inputconPassword.getText().toString().trim());
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
String uid = firebaseuser.getUid();
ref.child(uid).setValue(myUserInsertObj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(SignUpActivity.this, "User data stored.",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), Main2Activity.class));
}
else
{
Toast.makeText(SignUpActivity.this, "Error.",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), Main3Activity.class));
}
}
});
}
}
});
}
});
}
private boolean validateForm()
{
boolean valid = true;
String email = inputEmail.getText().toString();
if (TextUtils.isEmpty(email))
{
inputEmail.setError("Required.");
valid = false;
}
String password =inputPassword.getText().toString();
String conpassword = inputconPassword.getText().toString();
if (TextUtils.isEmpty(password))
{
inputPassword.setError("Required.");
valid = false;
}
if (TextUtils.isEmpty(conpassword))
{
inputconPassword.setError("Required.");
valid = false;
}
if(email.length()>0 && password.length()>0 && conpassword.length()>0)
{
if (isEmailValid(email))
{
inputEmail.setError(null);
if (isValidPassword(password))
{
inputPassword.setError(null);
if (isValidPassword(conpassword))
{
inputconPassword.setError(null);
if (password.equals(conpassword))
{
return valid;
}
else
{
Toast.makeText(getApplicationContext(), "Password not matched.Try again.", Toast.LENGTH_SHORT).show();
valid = false;
}
}
else
{
Toast.makeText(getApplicationContext(), "Password must contains minimum 6 characters at least 1 Lowercase, 1 Uppercase and, 1 Number.", Toast.LENGTH_SHORT).show();
valid = false;
}
}
else
{
Toast.makeText(getApplicationContext(), "Password must contains minimum 6 characters at least 1 Lowercase, 1 Uppercase and, 1 Number.", Toast.LENGTH_SHORT).show();
valid = false;
}
}
else
{
Toast.makeText(getApplicationContext(), "Email invalid.", Toast.LENGTH_SHORT).show();
valid = false;
}
}
return valid;
}
public static boolean isEmailValid(String email)
{
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
public static boolean isValidPassword(final String password)
{
Pattern pattern;
Matcher matcher;
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
}
To store the user's email and password after sign up do this:
String email=inputEmail.getText().toString().trim();
String password=inputconPassword.getText().toString().trim();
FirebaseUser currentUser= task.getResult().getUser();
String userid=currentUser.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
ref.child("email").setValue(email);
ref.child("password").setValue(password);
Then you will have:
Users
userid
email: email_here
password: password_here
more info here:
https://firebase.google.com/docs/database/android/read-and-write
This answer may give you more insight about how firebase handle auth information (email+password)..
Such information is stored in a separate database so if you want to store user data then you have to do it yourself.
You can find here more details on how to store user data.
Why are you storing plain text password in Firebase? This is a terrible idea. Firebase Auth already hashes and salts your users' passwords. If you ever need to migrate to an external system they provide multiple tools to do so via CLI SDK and Admin SDK.
here is my code for sign up button. it seems like no changes from the previous, but this one works.
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = inputEmail.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (!validateForm())
{
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (task.isSuccessful())
{
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
firebaseUser = auth.getCurrentUser();
String uid = firebaseUser.getUid();
User my = new User(email,password);
ref.child(uid).setValue(my).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(SignUpActivity.this, "Sign Up successfully.",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), Main2Activity.class));
}
else
{
Toast.makeText(SignUpActivity.this, "Error.",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), Main3Activity.class));
}
}
});
}
else
{
Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
}
}
});
}
});
I have the following SignUp Activity that does not work properly: after the user receives the verification email and tries to sign in, the app crashes with a NullPointerException, as a new user entry in Firebase Realtime Database is not created. I noticed, though, during debugging, that if I set a breakpoint at where generateUser() is defined, a new database entry is created (the app crashes the same way, though).
What could be the solution here?
Any help would be highly appreciated.
Update: The emphasis here is not on NullPointerException, I can handle that. The question is why generateUser() is not being called.
public class SignUpActivity extends AppCompatActivity {
private EditText inputUsername, inputEmail, inputPassword;
private Button btnSignIn, btnSignUp;
private ProgressBar progressBar;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
if (user.isEmailVerified()) {
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
finish();
}
}
setContentView(R.layout.activity_sign_up);
btnSignIn = findViewById(R.id.sign_in_button);
btnSignUp = findViewById(R.id.sign_up_button);
inputUsername = findViewById(R.id.username);
inputEmail = findViewById(R.id.email);
inputPassword = findViewById(R.id.password);
progressBar = findViewById(R.id.progressBar);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignUpActivity.this, SignInActivity.class));
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = inputUsername.getText().toString().trim();
final String email = inputEmail.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (TextUtils.isEmpty(username)) {
Toast.makeText(getApplicationContext(), "Enter username!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
} else {
new GenerateUserAsyncTask().execute(username, email, password, 0);
}
}
});
}
class GenerateUserAsyncTask extends AsyncTask<Object, Void, Void> {
#Override
protected Void doInBackground(Object... params) {
String username = (String) params[0];
String email = (String) params[1];
String password = (String) params[2];
int score = (int) params[3];
generateUser(username, email, password, score);
return null;
}
#Override
protected void onPostExecute(Void result) {
sendVerificationEmail();
}}
});
}
public void sendVerificationEmail() {
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Signup successful, verification email sent", Toast.LENGTH_SHORT).show();
auth.signOut();
startActivity(new Intent(SignUpActivity.this, SignInActivity.class));
finish();
} else {
Toast.makeText(SignUpActivity.this, "Failed to send email!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
});
}
}
public void generateUser(String username, String email, String password, int score) {
FirebaseDatabase database = Utils.getDatabase();
DatabaseReference users = database.getReference("users");
User user = new User(username, email, password, score);
users.child(auth.getUid()).setValue(user);
}
}
I have found the solution. The problem is caused by the Realtime Database security rules: they only allow users to write to the database if they are authenticated. In my code, though, where generateUser() is called, users are not fully authenticated yet. So I need to generate new entries in the database after the user has clicked on the link in the verification email.