尝试使用 .push() 访问存储在 Firebase 中的对象

Trying to access objects stored in Firebase with .push()

我试图在 Firebase 中存储一些对象,然后再访问它们,但我在访问部分遇到了问题。我可以存储一个对象,然后检索它,但是当我使用 .push() 时,我不知道如何操作多个对象。

到目前为止,我尝试过的任何方法都没有奏效,文档也没有真正帮助。基本上,我有 2 个按钮和一个 TextView。一个按钮创建一个对象的实例并将其添加到 Firebase,另一个按钮应该读取它们并在 TextView 中显示它们的一些数据。

这是添加对象的方法:

public void startWorkout(View view) {
    DatabaseReference dbRef = database.getReference();
    Workout workout = new Workout(10,30,20,"The Gym");
    dbRef.child("workouts")
            .push()
    .setValue(workout);
}

这是获取对象的方法:

public void endWorkout(View view) {
    DatabaseReference dbRef = database.getReference();
    dbRef.child("workouts").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Workout firstWorkout = dataSnapshot.getValue(Workout.class);
            TextView textView = (TextView) findViewById(R.id.test_text_view_Workouts);
            textView.setText(firstWorkout.getLocation());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e(TAG, "firebase call didn't work!");

        }
    });


}

这是来自 firebase 的 JSON(我在 Firebase 控制台中编辑了一些值,因此值不完全相同是正常的):

{
"workouts" : {
"-KKdzxVp9DDOpBsvhU3_" : {
"endTime" : 30,
"location" : "Home",
"startTime" : 10,
"totalTime" : 20
},
"-KKdzy13b6_tyaiQbW9W" : {
"endTime" : 30,
"location" : "The Gym",
"startTime" : 10,
"totalTime" : 20
},
"-KKe--wkPRQYWhcCBpyF" : {
"endTime" : 30,
"location" : "The Gym",
"startTime" : 10,
"totalTime" : 20
}
}
}

这是我创建的锻炼 class:

public class Workout {



//    Declaring variables needed to store workout data
public long startTime;
public long endTime;
public long totalTime;
public String location;

//         Empty Constructor required for Firebase
public Workout(){
}

public Workout(long startTime, long endTime, long totalTime, String location) {
    this.startTime = startTime;
    this.endTime = endTime;
    this.totalTime = totalTime;
    this.location = location;
}

//    Calculate totalTime
public void calculateTotalTime(){
    this.totalTime = endTime - startTime;
}


//    Getters and Setters
public long getStartTime() {
    return this.startTime;
}

public void setStartTime(long startTime) {
    this.startTime = startTime;
}

public long getEndTime() {
    return this.endTime;
}

public void setEndTime(long endTime) {
    this.endTime = endTime;
}

public long getTotalTime() {
    return this.totalTime;
}

public void setTotalTime(long totalTime) {
    this.totalTime = totalTime;
}

public String getLocation() {
    return this.location;
}

public void setLocation(String location) {
    this.location = location;
}

}

我对编程还比较陌生,所以如果能得到任何帮助,我将不胜感激。谢谢!

没关系。我想到了!

这是多种因素的结合,但基本上,我的列表(它是 activity 的一部分,我没有放入上面的代码片段)没有正确实现,现在是:

   List<Workout> workouts = new ArrayList<Workout>();

我应用了此处 for-each 循环中的一些逻辑:how to get all child list from Firebase android