I started working with android studio in less than a month, so i am pretty new to this.
I am working on a login system with Firebase Authentication, and with Firebase Database. My idea is that after the login is done and confirmed i send the user to one of two activities, and to check which one to send them to i check if they have already filled a quiz (witch is a boolean inside their database).
My problem is that my onComplete
method runs first instead of my quizChecked
. Thanks to my log prints i know that i get the right value, but since the onComplete
runs first my boolean is always false...
How can i make the onComplete
fire after the quizResposta
method?
Thanks in advance!
Here are my main methods in this class:
private boolean quizChecked() {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
myRef.child("user: " + mAuth.getCurrentUser().getUid()).child("quizChecked")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if(snapshot.exists()) {
boolean a = snapshot.getValue(boolean.class);
if (a == true) { // if quiz is done
quizChecked = (boolean) snapshot.getValue();
Log.e("TAG", "here true: " + quizChecked);
} else {// if quiz not done
quizChecked = (boolean) snapshot.getValue();
Log.e("TAG", "here false or null: " + quizChecked);
}
Log.e("TAG", "AFTER quizChecked: " + quizChecked);
}else{
Toast.makeText(Activity_Login.this, "No User!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("onCancelled", " cancelled");
}
});
Log.e("TAG", "________: " + quizChecked);
return quizChecked;
}
private void loginVerification(String emailString, String passwordString) {
mAuth.signInWithEmailAndPassword(emailString, passwordString).addOnCompleteListener(
this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {// if quiz answered -> MainActivity
quizChecked = quizChecked();
if (quizChecked == true) {
Log.e("TAG", "here true in login: " + quizChecked);
Toast.makeText(Activity_Login.this, "Login Sucess",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Activity_Login.this, MainActivity.class);
startActivity(intent);
finish();
} else { // if quiz not answered -> activity_quiz
Log.e("TAG", "here false or null in login: " + quizChecked);
Toast.makeText(Activity_Login.this, "Login Sucess",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Activity_Login.this, Activity_Questionario.class);
startActivity(intent);
finish();
}
Log.e("TAG", "AFTER login: " + quizChecked);
} else {
Toast.makeText(Activity_Login.this, "Login Failure",
Toast.LENGTH_SHORT).show();
}
}
});
}