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

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
Boron
  • 99
  • 10
  • 34
  • You can also check **[this](https://stackoverflow.com/questions/49253026/firebase-auth-and-database/49256810)** out. – Alex Mamo Nov 12 '18 at 19:03

2 Answers2

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.

Community
  • 1
  • 1
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • 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 – Boron Nov 11 '18 at 16:39
  • 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();` – Peter Haddad Nov 11 '18 at 16:41
  • If you are just generating a random id do this `String userId=ref.push().getKey(); ref.child(userId).setValue(user);` – Peter Haddad Nov 11 '18 at 16:42
  • did you try it? – Peter Haddad Nov 11 '18 at 17:53
  • 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…` – Boron Nov 12 '18 at 03:31
  • * their respective scores – Boron Nov 12 '18 at 03:41
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/183472/discussion-between-user8284066-and-peter-haddad). – Boron Nov 12 '18 at 03:55
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) {

    }
});
ManishPrajapati
  • 459
  • 1
  • 5
  • 16