'How to switch case with fetched user data from Firebase [duplicate]

I am making an android application that requires users to input a city they live in on sign-up. Now, if user is already signed-on, I want the app to skip the main screen and jump to the map of the user's city. I managed to check if user is signed-on and skip the main screen, but I don't know how to properly fetch "city" variable.

I tried using switch case but it just crashes the app.

FirebaseAuth fAuth = FirebaseAuth.getInstance();
if(fAuth.getCurrentUser() != null){

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    FirebaseDatabase.getInstance().getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            city = dataSnapshot.child("City").getValue().toString();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });

    if(grad!=null) {
        switch (city) {

            case "city1":
                startActivity(new Intent(MainActivity.this, city1.class));
                break;
            case "city2":
                startActivity(new Intent(MainActivity.this, city2.class));
                break;
            case "city3":
                startActivity(new Intent(MainActivity.this, city3.class));
                break;
            default:
                break;
        }
    }
}


Solution 1:[1]

Firebase works on an async thread so the data city gets filled later. You can solve this issue by create a function with city as the parameter and call it inside onDataChange() method.

something like this

FirebaseAuth fAuth = FirebaseAuth.getInstance();
        if(fAuth.getCurrentUser() != null){

            String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
            FirebaseDatabase.getInstance().getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    city = dataSnapshot.child("City").getValue().toString();
                   if(grad!=null){
                     yourfunc(city)
                   }
                
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    throw databaseError.toException();
                }
            });


void yourfunc(string city){
 //your switch case
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mr.Code