Firebase,DataSnapshot转换为Model类

时间:2017-05-29 17:45:18

标签: android firebase firebase-realtime-database

我在使用Firebase数据库时将DataSnapshot投射到我的Model类时遇到问题。

我收到DataSnapshot的信息,当我把它变成toString()并记录它时,我在Database看到了正确的信息(值)。但是当我尝试将它转换为我的Model类时,我会看到我的默认值(零值)

  1. 参考

    E / Query getRef():https:// ******** / users / pZl7xHxREefHZu3Zgd7ZZBSJTmA2 / activities

  2. DataSnapshot.toString()

    E / Query DataS:DataSnapshot {key = activities,value = {29May201720:11:16 = {,elapsedTime = 0,currentTime = 170529201116,(...), myLocationsList = {(...)} //信息
    //当前时刻的最新数据

  3. 投射后的模型数据

  4. E / Query getVal():ResourcesFromActivity {averageSpeed = 0.0,maxSpeed = 0.0,averageStrokeRate = 0.0,totalMeters = 0} //默认为零

    1. 在单个节点上,它正在运行

      usersActivitiesRef = database.getReference(“message”); usersActivitiesRef.addValueEventListener(本);

    2. 代码:on onCreate():

          (mAuth.getCurrentUser() == null) {
              mAuth.getCurrentUser().reload();
          }
          else{
              mUser = FirebaseAuth.getInstance().getCurrentUser();
              usersActivitiesRef = database.getReference("users").child(mUser.getUid()).child("activities");//.endAt(true).limitToLast(1);
      
             // usersActivitiesRef = database.getReference("message");
              Query query = usersActivitiesRef.orderByChild("currentTime").limitToLast(1);
              Log.e("Query getRef()",query.getRef().toString());
              //usersActivitiesRef.addValueEventListener(this);
              query.addValueEventListener(this);
          }
      

      关于数据更改

      @Override
      public void onDataChange(DataSnapshot dataSnapshot){
          ResourcesFromActivity receivedData = dataSnapshot.getValue(ResourcesFromActivity.class);
          Log.e("Query Ref",dataSnapshot.getRef().toString());
          Log.e("Query DataS","\n "+dataSnapshot.toString() );
          Log.e("Query getVal()","\n "+ receivedData.toString() );
          Log.e("Query","\n "+ Long.toString(receivedData.getTotalMeters()));
          allLocations = receivedData.getMyLocationsList();
        (...)
      

      型号:

      @IgnoreExtraProperties
      public class ResourcesFromActivity {
      
      public String currentTime;
      public long elapsedTime;
      public String elapsedTimeStr;
      public float averageSpeed;
      public float maxSpeed;
      public float averageStrokeRate;
      public long totalMeters;
      public List<MyLocation> myLocationsList = new ArrayList<>();
      public List<Location> allLocations = new ArrayList<>();
      public List<Float> allStrokes = new ArrayList<>();
      
      public ResourcesFromActivity(){
          // Default constructor required for calls to DataSnapshot.getValue(ResourcesFromActivity.class)
      } 
      public ResourcesFromActivity(String currentTime, long elapsedTime, String elapsedTimeStr, float averageSpeed, float maxSpeed, float averageStrokeRate, long totalMeters, List<MyLocation> myLocationsList, List<Location> allLocations, List<Float> allStrokes) {
          this.currentTime = currentTime;
          this.elapsedTime = elapsedTime;
          this.elapsedTimeStr = elapsedTimeStr;
          this.averageSpeed = averageSpeed;
          this.maxSpeed = maxSpeed;
          this.averageStrokeRate = averageStrokeRate;
          this.totalMeters = totalMeters;
          this.myLocationsList = myLocationsList;
          this.allLocations = allLocations;
          this.allStrokes = allStrokes;
      }
      

      也许我做错了索引

      {
        "rules": {
          "users": {
            "$uid": {
              ".read": "true",
              ".write": "$uid === auth.uid",
              "$userId" :{
              "activities":{
               "$activitieId": {
                 ".read": "true",
                 ".indexOn": ["currentTime"]
               }
              }
            }
            },
      
      }
      }
      

      }

      谢谢

1 个答案:

答案 0 :(得分:1)

看起来这里的问题是你作为dataSnapshot取回的内容与你期望获得的内容略有不匹配。

在这种情况下你得到的不是单个活动记录,它是一个活动记录图,在这种情况下包含一个项目(或一个孩子),因为这是你在查询中指定的内容。

因此,这很重要,因为您不能直接将此地图设置为ResourcesFromActivity类,即使地图只包含一个项目,预期的字段也不匹配。

使用当前设置执行此操作的一种方法是修改onDataChange,如下所示:

@Override
public void onDataChange(DataSnapshot dataSnapshot){
    for(DataSnapshot activitySnapShot: dataSnapshot.getChildren()){
        ResourcesFromActivity receivedData = activitySnapShot.getValue(ResourcesFromActivity.class);
    }
}

现在我们在迭代dataSnapshot的子节点以获取子节点的活动数据。在这种情况下,它只有一个孩子,但你可以修改以处理多个孩子。