最近,我在android应用程序中使用firebase,并尝试使用nosql数据结构,但遇到了一些问题。
首先,我的数据结构非常简单:
{
"user": {
"userid1" :{
"id: "userid1"
"name": "Samantha",
"age": 25
"email" : "abc@gmail.com"
}
}
}
所以我这样写了我的实体类
public class User implements Serializable {
private String id;
private String name;
private int age;
private String email;
}
当我想让所有用户进入列表时:
FirebaseDatabase.getInstance().getReference("user").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
listUser.add(user);
}
}
}
但是如果我想像这样改变我的数据结构,我不知道怎么做:
{
user: {
userid1 :{
id: "userid1"
name: "Samantha",
age: 25
email : "abc@gmail.com"
posts:{
postid1: {
postid : "postid1"
content : "content1"
}
postid2: {
postid : "postid2"
content : "content2"
}
}
}
}
}
我想我必须创建一个post实体类,但是如何像以前一样获取用户列表呢?任何人能向我解释都会有帮助。
1条答案
按热度按时间pieyvz9o1#
像您想做的那样嵌套数据是firebase中的一种反模式,与数据结构文档中的建议背道而驰。看到了吗https://firebase.google.com/docs/database/android/structure-data#best_practices_for_data_structure
也就是说:如果你有这样一个结构,你可以通过添加
posts
Map到类以读取其数据:如果您想让他们安全地键入,您可能需要使用
GenericTypeIndicator
.