【发布时间】:2017-04-07 02:37:15
【问题描述】:
我正在开发 Android 应用程序,其中 Firebase 用于维护移动后端。我在Firebase上有这种格式的数据库
{
"users" : {
"-Kh2wjxeT-w26opA0yqe" : {
"email" : "XX@gmail.com",
"firstName" : "XX",
"interest" : {
"interests" : [ "Cricket", "Table Tennis", "Football" ]
},
"lastName" : "XXX",
"password" : "abcd@1234"
}
}
}
Users.java
@IgnoreExtraProperties
public class User {
public String firstName;
public String lastName;
public String email;
public String password;
public Interest interest;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String firstName, String lastName, String email, String password, Interest interest) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.interest = interest;
}
}
兴趣.java
public class Interest {
public List<String> interests;
public Interest() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public Interest(List<String> interests) {
this.interests = interests;
}
}
我以这种方式在子“用户”上添加了addValueEventListener
mDatabase.child("users").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) {
User user = dataSnapshot.getValue(User.class);
Log.d("Scheduled", user.firstName + user.lastName + user.interest.interests.toString());
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
它正在获取我在Firebase 上的正确数据,但它没有映射Users java 对象中的数据,所以当我无法访问值时。我不确定我在这里犯了什么错误。
Log.d("预定", user.firstName + user.lastName + user.interest.interests.toString());
【问题讨论】:
-
在您的
Interest类中,不要使用List<String>,而是使用Map<String, Object>。它肯定会起作用。并且不要忘记在模型类中设置公共设置器和获取器。 -
我猜问题是因为创建了唯一 ID `“-Kh2wjxeT-w26opA0yqe”,而我在
User.java中没有类似的东西 -
@AlexM。我也尝试了`HashMap,但它不起作用
-
威廉姆斯,请改造你的班级。删除您的
Interest类并在User类中创建一个名为interest的Map。而不是创建公共 setter 和 getter。 -
@AlexM。我已经完成了pastebin.com/hvM8TxbK 它不工作
标签: android firebase firebase-realtime-database