0

I'm a newbie to Firebase and I'm trying to get data from cloud to my project

DatabaseReference userRef = ref.child(user.getUid());

    userRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            UserDoctor userDoctor = dataSnapshot.getValue(UserDoctor.class);
            tempName = userDoctor.getName();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

But the problem is I couldn't assign the string to the tempName, it returned "null"

This is my debug window

And the UserDoctor class is here

public class UserDoctor {
public String address;
public String major;
public String mobile;
public String name;
public String workplace;

public UserDoctor(){}

public UserDoctor(String _address, String _major, String _mobile, String _name, String _workplace){
    name = _name;
    address = _address;
    major = _major;
    mobile = _mobile;
    workplace = _workplace;
}

public String getName() {
    return name;
}

}

Thank you very much!

KENdi
  • 7,576
  • 2
  • 16
  • 31
  • As your debug window shows, the name of the doctor is being property read and set. The problem is not reading the data from Firebase. The problem is more likely *when* you are trying to use `tempName`. Data is read from Firebase asynchronously and most likely simply hasn't been read yet when you are using `tempName`. See my answer here for a long explanation: http://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener – Frank van Puffelen Mar 23 '17 at 16:03
  • @FrankvanPuffelen First of all, thanks for your answer, I've read the link you gave but I'm so confused and don't know what to do with this. So I can't use the semaphore, right?. Can you suggest me a way to get the doctor's name? – Phụng Nguyễn Lê Gia Mar 23 '17 at 16:19
  • Your code already *gets* the doctor's name. But you show nowhere how your using it. Typically you'll need to move all the code that *uses* `tempName` *into* `onDataChange()`. – Frank van Puffelen Mar 23 '17 at 17:07
  • intent.putExtra("userName", tempName); I already did it, but it seemed not worked well – Phụng Nguyễn Lê Gia Mar 24 '17 at 01:04
  • That depends on where you use that code. If the link I provided (which is the most likely cause, I'm quite certain of that) doesn't help you solve the problem, please edit your question to include a [single, minimal snippet of code that completely reproduces the problem](http://stackoverflow.com/help/mcve) (read the link, it's quite useful). – Frank van Puffelen Mar 24 '17 at 03:23

0 Answers0