从Firebase数据库通过多个路径获取数据

时间:2018-11-15 10:18:06

标签: java android firebase firebase-realtime-database

我从多个路径从Firebas eDatabase获取数据时遇到问题。我正在编写Endomondo克隆,并且具有如下数据库结构:

users:
    user_1:
        name:
        ....
        friends:
            user_2
            user_3
    user_2:
        ...
workouts:
    user_1:
        workout_1:
            distance:
            duration:
            path:
            etc.
    user_2:

现在,我想在“ Feed”标签中列出朋友的所有锻炼。为此,我需要做三件事。

1)遍历我的个人资料(用户_1)以获取我所有的朋友ID。

2)当我拥有这些ID时,我需要遍历它们的配置文件以显示其名称。

3)反复进行锻炼,以获取朋友的所有锻炼。
现在,我想将所有这些信息放在一个对象中,让我们说“ FriendWorkout”,它看起来像:

FriendWorkout:
    String friendName;
    Workout workout; // contains all workout data(path, time, distance)

并将所有这些对象放在列表中,以便我可以将其传递给适配器。

JSON:

{
  "users" : {
    "BLhXU5eJGtZayRrUGYTrGiImg313" : {
      "avatarUrl" : "https://firebasestorage.googleapis.com/v0/b/alphaui-40ee2.appspot.com/o/avatars%2Favatars%2FBLhXU5eJGtZayRrUGYTrGiImg313.jpg?alt=media&token=c6b00937-6970-4f43-8ea4-b9add33c43e1",
      "email" : "xhh@gmail.com",
      "firstName" : "Jadwiga",
      "friends" : {
        "CTS134a7vtMWcBs7N2ynDKSyKj23" : true,
        "DoXUtoa7vtMWcBs7N2ynDKSyKj23" : true
      },
      "lastWorkout" : "-LRGN8H6a1esdUPvb-ve",
      "surname" : "Szalony"
    },
    "CTS134a7vtMWcBs7N2ynDKSyKj23" : {
      "avatarUrl" : "none",
      "email" : "ofca@wp.pl",
      "firstName" : "Leokadia",
      "friends" : {
        "BLhXU5eJGtZayRrUGYTrGiImg313" : true
      },
      "lastWorkout" : "dasdsa",
      "surname" : "Fin"
    }
  },
  "workouts" : {
    "BLhXU5eJGtZayRrUGYTrGiImg313" : {
      "-LRGN3sEJgrNxRH3Hf6j" : {
        "date" : "Wed, 14 Nov 2018 09:39:41",
        "distance" : 0,
        "duration" : "0:00",
        "workoutName" : "Running"
      },
      "-LRGN68Z_s5dUjlkuhB-" : {
        "date" : "Wed, 14 Nov 2018 09:39:50",
        "distance" : 0,
        "duration" : "0:00",
        "workoutName" : "Running"
      }
    },
    "DoXUtoa7vtMWcBs7N2ynDKSyKj23" : {
      "-LRGSafxbmKWGLy5x-Kd" : {
        "date" : "Wed, 14 Nov 2018 10:03:50",
        "distance" : 0,
        "duration" : "0:02",
        "workoutName" : "Running"
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您需要解决的问题可以通过查询数据库三次来解决,一次获取friendUid,第二次获取对应的names,第三次获取对应的Workout个对象朋友们。因此,请使用以下代码行:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendsRef = rootRef.child("users").child(uid).child("friends");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String friendUid = ds.getKey();

            DatabaseReference friendUidRef = rootRef.child("users").child(friendUid);
            ValueEventListener eventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot ds : dataSnapshot.getChildren()) {
                        String firstName = ds.child("firstName").getValue(String.class);
                        String surname = ds.child("surname").getValue(String.class);
                        String friendName = firstName + " " + surname;
                        Log.d(TAG, friendName);

                        DatabaseReference friendUidWorkoutsRef = rootRef.child("workouts").child(friendUid);
                        ValueEventListener listener = new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                List<FriendWorkout > workouts = new ArrayList<>(); //List added
                                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                                    Workout workout = ds.getValue(Workout.class);
                                    Log.d(TAG, workout.getWorkoutName());

                                    //Create an object of FriendWorkout as needed
                                    FriendWorkout friendWorkout = new FriendWorkout(friendName, workout);
                                    workouts.add(friendWorkout); //Add object to the list
                                }
                                ListView listView = (ListView) findViewById(R.id.list_view);
                                ArrayAdapter<Data> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
                                listView.setAdapter(arrayAdapter); //Set the adapter
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {
                                Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
                            }
                        };
                        friendUidWorkoutsRef.addListenerForSingleValueEvent(listener);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
                }
            };
            friendUidRef.addListenerForSingleValueEvent(eventListener);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
friendsRef.addListenerForSingleValueEvent(valueEventListener);