1

I am doing a project with firebase, able to save some records on the database, but retrieving it has been an issue for me, I've meddled with other posts from SO but they haven't worked for me. This is how the database looks like (An example):

enter image description here

And my code for retrieving the data:

private void readDataFromDB() {
    databaseReference.child("users").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            User user = new User();
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                user.setStrName(//Get the Name of the user);
                user.setStrScore(//Get the Score of the user));
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

The User class:

public class User {
  String strName, strScore;

  public String getStrName() {
      return strName;
  }

  public void setStrName(String strName) {
      this.strName = strName;
  }

  public String getStrScore() {
      return strScore;
  }

  public void setStrScore(String strScore) {
      this.strScore = strScore;
  }
}

How can I get the name and score from each specific user

1
  • You can also check this out. Commented Nov 12, 2018 at 19:03

2 Answers 2

2

In your code, you are setting values, you need to be retrieving values using the getters.

Try the following:

databaseReference.child("users").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            User user    = dataSnapshot.getValue(User.class);
            String name  = user.getStrName();
            String score = user.getStrScore();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

But, first you need to add the values to the database example:

User user = new User();
user.setStrName("my_name");
user.setStrScore("20");

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
ref.push().setValue(user);

Note setValue():

In addition, you can set instances of your own class into this location, provided they satisfy the following constraints:

  1. The class must have a default constructor that takes no arguments
  2. The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized

You need to add a default constructor to the POJO class public User(){} and also the field names in the class should match the ones in the database. So change this String strName, strScore; into this String name, score; and generate the getters and setters again.

Sign up to request clarification or add additional context in comments.

7 Comments

I modified my POJO class to match the field names. Do I have to set the data to the POJO first before I push to database, secondly, how do I get the userID, since it is a specific random value for every user
yes first set the data to add to the database then retrieve, by userid do you mean the id from firebase authentication? If so then do FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ; String userId=currentFirebaseUser.getUid();
If you are just generating a random id do this String userId=ref.push().getKey(); ref.child(userId).setValue(user);
did you try it?
Yes sir, but my issue was that I'm trying to display all the names and their respective columns, after getting the users, that is databaseReference.child("users").child(//what to pass here to get Firebase authentication id ->getKey() won't allow me to add another child chain after it).child("profile").addValueEventListener…
|
0

Instead of creating profile in every node you can use a global profile node, and in that store the profile data with their UID, which would make it easier for you to fetch detail of single user.

-profile
  -UID1
    -name
    -score
  -UID2
    -name
    -score

While retrieving you can use getCurrentUser.getUid() to retrieve data for each user:

 String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference.child("users").child("profile").child(uid).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        User user = new User();

           user = dataSnapshot.getValue(User.class);

    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.