i'm having a problem with my app. I built a simple login / logout app and it work normally, i want to toast a message every time the user login back but it toasted an empty string ( i log it in logcat and it show up normally ) , i don't know why and how to fix it . Please help me and tell me if there's better way to get this data from Firebase.
Bellow is the code :
String username = ""; //TO STORE USERNAME - Global variable
private void loginUser(String txt_email, String txt_password) {
auth.signInWithEmailAndPassword(txt_email, txt_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("firebase_debug", "signInWithEmail:success");
//GET USER NAME
FirebaseUser user = auth.getCurrentUser();
DatabaseReference username_ref = db.getReference("Users");
username_ref.child(user.getUid()).child("username").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
Log.d("firebase", String.valueOf(task.getResult().getValue())); // THIS LINE STILL WORK , IT DO LOG THE CORRECT USERNAME
username=String.valueOf(task.getResult().getValue());
}
}
});
Toast.makeText(MainActivity.this,username,Toast.LENGTH_SHORT).show();//TOAST EMPTY STRING ??
startActivity(new Intent(MainActivity.this,ChatRoom_Activity.class));
finish();
} else {
// If sign in fails, display a message to the user.
Log.d("firebase_debug", "signInWithEmail:failure", task.getException());
login_btn.setText("LOGIN");
login_btn.setEnabled(true);
password_input.setText("");
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull @NotNull Exception e) {
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}