Firebase实时数据库,从键值对中获取数据

时间:2018-11-17 09:16:52

标签: java android firebase firebase-realtime-database

我正在创建我的第一个android firebase测试项目,并且在尝试取回数据时遇到问题。这是我的数据在控制台中的样子:

enter image description here

和我的代码以获取年龄和姓名:

databaseReference.child("users").child(firebaseUserId).child("profile")
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        Users users = snapshot.getValue(Users.class);

                        Toast.makeText(LoginActivity.this, "Name: " + users.getName() + "\n" +
                                "Gender: " + users.getGender(), Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

和User(POJO)类如下:

public class Users {
String name, gender;

public Users() {
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}
}

但是,我无法执行此操作,程序因以下错误而崩溃:

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type project.ibrapptly.com.kcpe_tests_and_quizzes.Users

如何获取数据,或者最有效的方法是什么?

1 个答案:

答案 0 :(得分:1)

更改此:

databaseReference.child("users").child(firebaseUserId).child("profile")
        .addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Users users = snapshot.getValue(Users.class);

                    Toast.makeText(LoginActivity.this, "Name: " + users.getName() + "\n" +
                            "Gender: " + users.getGender(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

对此:

databaseReference.child("users").child(firebaseUserId).child("profile")
        .addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                    Users users = dataSnapshot.getValue(Users.class);

                    Toast.makeText(LoginActivity.this, "Name: " + users.getName() + "\n" +
                            "Gender: " + users.getGender(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

在这种情况下,您需要删除for循环。循环时,您将检索类型为String的属性agename