Java Firebase按值获取数据

时间:2017-05-13 08:57:47

标签: java android firebase firebase-realtime-database

我一直在强调这个firebase,我有这样的数据

{
  "PSNPR-5I2VG" : {
  "data1" : "data1",
  "data2" : "data2",
  "data3" : "data3",
  "condition" : "false"
},
  "PSNPR-P2286" : {
  "data1" : "data1",
  "data2" : "data2",
  "data3" : "data3",
  "condition" : "true"
}
}

我有很多像上面这样的数据,但我只得到条件= true的数据,所以这是我的java代码:

mRef.orderByChild("condition").equalTo("true").addChildEventListener(new com.firebase.client.ChildEventListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
 @Override
     public void onChildAdded(DataSnapshot child1, String s) {

        for (DataSnapshot child2: child1.getChildren()) {
            String data1 = (String) child2.child("data1").getValue();
             Log.e("data1 "data1);
        }

     }

  });

我希望从条件=" true"的数据中获取data1,data2,data3,它与where条件一起工作,但我无法按键获取单个数据

String data1 = (String) child2.child("data1").getValue();
                 Log.e("data1 "data1);

错误

 java.lang.NullPointerException: println needs a message

请帮助各位,我是新的java android和firebase。

1 个答案:

答案 0 :(得分:0)

您可以使用Map获取所有数据:

Map<String, String> dataInfo = (Map<String, String>)dataSnapshot.getValue();

for(Object info: dataInfo.values())
   {
     Map<String, String> obj= (Map<String, String>)info;
     final String data1= obj.get("data1"); 
     final String data2= obj.get("data2");
     final String data3= obj.get("data3");
   }