0

When I read a Firebase database, the city and town variables show me to as null. Why?

Denemesiralamaisyerleri deneme = new Denemesiralamaisyerleri();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String id = firebaseUser.getUid();
DatabaseReference userdata = FirebaseDatabase.getInstance().getReference().child("users").child(id);

ValueEventListener rdn = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) { // Read user info from the database
        deneme = dataSnapshot.getValue(Denemesiralamaisyerleri.class);

    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Toast.makeText(UserInterfaceBerber.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
    }
};

userdata.addValueEventListener(rdn);
city = deneme.getCity();
town = deneme.getTown();
ilin.setText(city);
ilcenin.setText(town);
Toast.makeText(UserInterfaceBerber.this, city + " " + town + " ", Toast.LENGTH_LONG).show();

My database structure like this:

users
igORGoET3gT6i8CV4wvtuN3l08z1
city:
"Antalya"
email:
"ahmetbulur@gmail.com"
namesurname:
"Ahmet bulur"
phonenum:
"05346789445"
town:
"Alanya"

Also, for this toast message, the "city" and "town" variable show as null. I expect that it shows me "Antalya" + "Alanya" for the toast message:

Toast.makeText(UserInterfaceBerber.this, city + " " + town + " ", Toast.LENGTH_LONG).show();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
normin48
  • 15
  • 4

1 Answers1

0

Because the data is loaded from Firebase asynchronous, you should use that data only when the operation completes, and this only inside the onDataChange() method, like in the following lines of code:

Denemesiralamaisyerleri deneme=new Denemesiralamaisyerleri();
FirebaseUser firebaseUser=firebaseAuth.getCurrentUser();
String id=firebaseUser.getUid();
DatabaseReference userdata=FirebaseDatabase.getInstance().getReference().child("users").child(id);
ValueEventListener rdn=new ValueEventListener() {
    @Override
    public void onDataChange( DataSnapshot dataSnapshot) {     //read user info from database
        deneme=dataSnapshot.getValue(Denemesiralamaisyerleri.class);
        city=deneme.getCity();
        town=deneme.getTown();
        ilin.setText(city);
        ilcenin.setText(town);
        Toast.makeText(UserInterfaceBerber.this,city+" "+town+" ",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Toast.makeText(UserInterfaceBerber.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
    }
};
userdata.addValueEventListener(rdn);

For more info, I recommend you see the last part of my answer from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193