Showing Firebase data in ListView
This is a classic issue with asynchronous APIs. In order to make it work, change your model class according to Java Naming Conventions. Your class should look like this:
public class Score {
private String userId, score;
public Score() {}
public Score(String userId, String score) {
this.userId = userId;
this.score = score;
}
public String getUserId() {
return userId;
}
public String getScore() {
return score;
}
@Override
public String toString() {
return "Score{" +
"userId='" + userId + '\'' +
", score='" + score + '\'' +
'}';
}
}
Also note that onDataChange()
method has an asynchronous behavior, which means that is called even before you are trying to add those objects of Score
class to the list. In other words, your list
will always be empty outside that method. A quick fix would be to move the declaration of your list inside onDataChange()
and do what you want to do with it or, if you want to dive into the asynchronous world and use my answer from this post.
Assuming the score
node is a direct child of your Firebase root, to display the data using the String class, please use the following code:
ListView listView = (ListView) findViewById(R.id.list_view);
List<String> list = new ArrayList<>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("userId").getValue(String.class);
String score = ds.child("score").getValue(String.class);
list.add(userId + " / " + score);
Log.d("TAG", userId + " / " + score);
}
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, task.getException().getMessage());
}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
And this how you can display data using the Score
class.
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Score score = ds.getValue(Score.class);
String userId = score.getUserId();
String score = score.getScore();
Log.d("TAG", userId + " / " + score);
list.add(score);
}
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, task.getException().getMessage());
}
};
scoreRef.addListenerForSingleValueEvent(eventListener);