如何在java中使用FirebaseListAdapter从firebase数据库中读取子元素?

时间:2016-12-22 11:14:13

标签: java android firebase firebase-realtime-database

我是Firebase的新手。所以,我有一个像这样的数据库结构:

enter image description here

并希望将生成的ID显示在列表视图中。我使用的是FirebaseListAdapter。这是我的代码:

    databaseReference = FirebaseDatabase.getInstance().getReference().child("Firebase").child("Users");
    firebaseListAdapter = new FirebaseListAdapter<String>(this, String.class, android.R.layout.simple_list_item_1, databaseReference) {
        @Override
        protected void populateView(View v, String string, int position) {
            TextView textView = (TextView) v.findViewById(android.R.id.text1);
            textView.setText(string);
        }
    };
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(firebaseListAdapter);

这是我的用户类:

class User {
private String userName;
private String email;

    void setUserName(String userName) {this.userName = userName;}
    String getUserName() {return userName;}

    void setEmail(String email) {this.email = email;}
    String getEmail() {return email;}
}

当我复制此内容时,我收到此错误:com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String

我该如何解决这个问题?

提前致谢!

2 个答案:

答案 0 :(得分:1)

populateView方法实现更改为

firebaseListAdapter = new FirebaseListAdapter<User>(this, User.class, android.R.layout.simple_list_item_1, databaseReference) {
    @Override
    protected void populateView(View v, User user, int position) {
        TextView textView = (TextView) v.findViewById(android.R.id.text1);
        String userKey = this.getRef(position).getKey();
        textView.setText(userKey);
    }
};

答案 1 :(得分:0)

您需要FirebaseListAdapter<Map>代替FirebaseListAdapter<String>。你的代码会变成这样的东西(虽然没有编译它,但这取决于你; - )

databaseReference = FirebaseDatabase.getInstance().getReference().child("Firebase").child("Users");
firebaseListAdapter = new FirebaseListAdapter<Map>(this, Map.class, android.R.layout.simple_list_item_1, databaseReference) {
    @Override
    protected void populateView(View v, Map users, int position) {
        TextView textView = (TextView) v.findViewById(android.R.id.text1);
        textView.setText(users.getKey());
    }
};
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(firebaseListAdapter);