Showing Firebase data in ListView

2019-01-03 00:35发布

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

2条回答
闹够了就滚
2楼-- · 2019-01-03 00:52

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:

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 behaviour, which means that is called even before you are trying to add those objects of Score class to the list. With 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:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        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);
        }
        ListView listView = (ListView) findViewById(R.id.list_view);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
        listView.setAdapter(arrayAdapter);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
scoreRef.addListenerForSingleValueEvent(eventListener);

And this how you can display data using Score class.

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<Score> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Score s = ds.getValue(Score.class);
            String userId = s.getUserId();
            String score = s.getScore();
            Log.d("TAG", userId + " / " +  score);
            list.add(score);
        }
        ListView listView = (ListView) findViewById(R.id.list_view);
        ArrayAdapter arrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, list);
        listView.setAdapter(arrayAdapter);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
查看更多
放我归山
3楼-- · 2019-01-03 00:53

filepath.addOnSuccessListener(upload data first) then get it and use it....

查看更多
登录 后发表回答