0

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();
        }
    });
}
phvtquang
  • 35
  • 5
  • Just move the `Toast` into the correct call-back method. – Martin Zeitler Jun 25 '21 at 19:01
  • Write toast within else{} block. – androidLearner Jun 25 '21 at 19:02
  • I got yours ideas , but can i ask why my code not work , i think because it was stored in the String variables so why it's empty when i toast outside. – phvtquang Jun 25 '21 at 19:05
  • It's because your ` Toast.makeText(MainActivity.this,username,Toast.LENGTH_SHORT).show()` runs **before** the `username=String.valueOf(...)` ever executes. If you run the code in a debugger, or add some `Log.d()` statements, you can most easily see this. The rule is pretty simple: any code that needs data from the database needs to be inside the `onComplete` handler (or be called from there). – Frank van Puffelen Jun 25 '21 at 19:10
  • 1
    Thanks for your comment, I understood my problem better. @FrankvanPuffelen – phvtquang Jun 25 '21 at 19:14
  • I think you also might be interested in this article, [How to read data from Firebase Realtime Database using get()?](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5). – Alex Mamo Jun 28 '21 at 16:09

0 Answers0