I have a firebase realtime database and want to use the data to make a leaderboard. Im trying to retrieve all the data in my Scores node but am not sure how to loop through to g
It appears as though you are using a "Listener" class to access the data and print out the scores. The "ValueEventListener" listener you attached, with the "onDataChange()" method implemented, would not be called until there is a data change.
I'm not sure how you are using this class, but based on your question, I am assuming that you just want to print the scores when the "leaderboard.onCreate()" method is executed. Is this correct? If that is the case, you may not need to be attaching a listener.
You're going one level too deep into your JSON and are reading /Points/Points
. Since that node doesn't exist, you get an empty snapshot in your onDataChange
.
database.getReference().child("Scores").addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Log.i(TAG, "The scores are " + dataSnapshot.child("Points").getValue(Long.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
New Code that returns values:
public class leaderboard extends AppCompatActivity {
DatabaseReference databaseUsers;
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseAuth mAuth;
TextView score;
private static final String TAG = "leaderboard";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
score = (TextView) findViewById(R.id.tableText);
database.getReference().child("Scores").addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
System.out.println("The score is: " + snapshot.toString());
score.setText(snapshot.toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
}
}
This is my progress: