samsa
samsa

Reputation: 78

datasnapshot doesn't get value from firebase

I guess the problem must be there but I couldn't figure it out. I want to reach the title but I can't always snapshot returns null also no problem about connection because when I check user id I can reach that.

  DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference titleRef = rootRef.child("users").child("value").child("title");
    button.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View view) {
            titleRef.get().addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    DataSnapshot snapshot = task.getResult();
                    String title = snapshot.getValue(String.class);
                    Log.d("TAG", title);
                    System.out.println(title);
                } else {
                    Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
                }
            });
        }
    });

enter image description here

----my data structure----

{
  "users" : {
    "value" : {
      "title" : "dsfdfasd"
    }
  }
}

Upvotes: 3

Views: 503

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

If your database schema looks like this:

{
  "users" : {
    "value" : {
      "title" : "dsfdfasd"
    }
  }
}

To be able to get the value of "title", please use the following reference

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference titleRef = rootRef.child("users").child("value").child("title");

Call get() and attach a listener like this:

titleRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            String title = snapshot.getValue(String.class);
            Log.d("TAG", title);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

The result in the logcat will be:

dsfdfasd

Besides that, always log the error instead of blindly assuming that everything works fine.

Upvotes: 1

Exron
Exron

Reputation: 103

Your data structure is not compatible with your code

ref.child(userID)....

There is no uid in your data structure. Instead you have value.

Upvotes: 0

Related Questions