Okay so I got it to run showing the User ID but not score. I then began making some changes, forgot what I'd changed and now I'm back to null null again. I feel like I may have deleted something or misspelled something.
dbref.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> list = new ArrayList<>();
list.clear();
for(DataSnapshot ds :dataSnapshot.getChildren()) {
Score Result = ds.getValue(Score.class);
String userId = String.valueOf(Result.getUserId());
String score = String.valueOf(Result.getScore());
list.add(userId);
list.add(score);
}
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, list);
LvRanking.setAdapter(adapter);
}
Here's my model:
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 + '\'' +
'}';
}
}
Database: Link to my database screenshot
This is a classic issue with asynchronous APIs. In order to make it work, change your model class acording to Java Naming Conventions. You class should look like this:
Also note that
onDataChange()
method has an asynchronous behaviour, which means that is called even before you are trying to add those objects ofScore
class to the list. With other words, yourlist
will always be empty outside that method. A quick fix would be to move the declaration of your list insideonDataChange()
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:And this how you can display data using
Score
class.filepath.addOnSuccessListener(upload data first) then get it and use it....