我只想检索活动id1和id2,以便将其保存在列表中。但是,我这样做,最后一行返回整个对象引用
{Category 1={name=joy, Sprint={Activities={id2=23r90u9329r,
id1=jf92jf943jf94j3f9}, startingDate =08092017, sprintOverallScore=1,
Ending Date=08092017, Number of Weeks=2}}
我如何才能获得Activities={id2=23r90u9329r,
id1=jf92jf943jf94j3f9}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
//getting the reference of artists node
databaseCategories = FirebaseDatabase.getInstance().getReference("Categories");
databaseCategories.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clear the list
currentCategories.clear();
//iterate through all the node
for(DataSnapshot postsnapshot: dataSnapshot.getChildren()){
//Category j = postsnapshot.getValue(Category.class);
System.out.println("test: " + postsnapshot.getValue());
我尝试创建这样的2个数据库引用,但它返回NULL:
DatabaseReference databaseCategories, databaseCategories2;
....
databaseCategories.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clear the list
currentCategories.clear();
//iterate through all the node
for(DataSnapshot postsnapshot: dataSnapshot.getChildren()){
String g = postsnapshot.getKey(); //get the id
databaseCategories2 = FirebaseDatabase.getInstance().getReference("CategoryNew").child(g+"").child("Category 1").child("Sprint").child("Activities");
databaseCategories2.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("test new: " + dataSnapshot.getValue()); //returning NULL
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
答案 0 :(得分:0)
由于您在/Categories
上附加了一个监听器,因此onDataChange
将调用dataSnapshot
,其中包含完整值。你循环遍历其子级,这会让你降低一级,但是postSnapshot
仍然是hsdhs...
下的整个数据。您还需要在代码中导航快照的其余部分,以进入活动:
databaseCategories = FirebaseDatabase.getInstance().getReference("Categories");
databaseCategories.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//iterate through the categories
for(DataSnapshot categorySnapshot: dataSnapshot.getChildren()){
DataSnapshot activitiesSnapshot = categorySnapshot.child("Category1/Sprint/Activities");
for(DataSnapshot activitySnapshot: activitiesSnapshot.getChildren()){
System.out.println(activitySnapshot.getKey()+": "+activitySnapshot.getValue(String.class));
}
}
}
...
请注意,这非常浪费,包括您必须编写的代码量和检索的数据量。如果您的应用中有一个常见的用例来查找某个类别的活动,请考虑将这些用作顶级列表存储:
CategoryActivities
CategoryId
ActivityId1: "value 1"
ActivityId2: "value 2"
使用此结构,您可以更轻松地精确读取所需的数据,从而节省数据传输和深层嵌套代码。