I'm trying to store some objects in Firebase, and then access them after, but I'm having trouble with the accessing part. I can store one object, and retrieve that, but when I use .push() I can't figure out how to manipulate multiple objects.
So far, nothing I've tried has worked, and the documentation hasn't really helped either. Basically, I have 2 buttons and a TextView. One button creates instances of an object and adds it to to Firebase, and the other one is supposed to read them and display some data from them in the TextView.
This is the method to add objects:
public void startWorkout(View view) {
DatabaseReference dbRef = database.getReference();
Workout workout = new Workout(10,30,20,"The Gym");
dbRef.child("workouts")
.push()
.setValue(workout);
}
This is the method to fetch the objects:
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!");
}
});
}
Here's the JSON from firebase (I edited some of the values in the Firebase console, so it's normal that the values aren't exactly the same) :
{
"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
}
}
}
And here's the Workouts class I created:
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;
}
}
I'm relatively new to programming, so I'd appreciate any help I can get. Thanks!