I am using the Real Time Database from Firebase on java for Android and I am trying to write a set of helper function to facilitate read and write functions from/to the RTDB.
My function looks like the following and is supposed to return a HashMap of my Parking objects on the database; I get a reference to my database and add an onSuccessListener
where I iterate through the snapshot and add each Parking
object to my HashMap and return the HashMap parkings
.
The problem is the function returns parkings
with no values in it before the onSuccessListener runs.
public static ArrayList<Parking> getParkingLots() {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
Task<DataSnapshot> dataSnapshotTask = mDatabase.get();
ArrayList<Parking> parkings = new ArrayList<Parking>();
dataSnapshotTask.addOnSuccessListener(new OnSuccessListener<DataSnapshot>() {
@Override
public void onSuccess(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> parkingsData = dataSnapshot.getChildren();
for (DataSnapshot parking :
parkingsData) {
parkings.add(parking.getValue(Parking.class));
}
}
});
return parkings;
}
I tried this implementation as well where I directly try and get the results from the Task datSnapshotTask
but I get an exeption thrown
java.lang.IllegalStateException: Task is not yet complete
.
public static HashMap<String, Parking> getParkingLots() {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
Task<DataSnapshot> dataSnapshotTask = mDatabase.get();
Iterable<DataSnapshot> parkingsData = dataSnapshotTask.getResult().getChildren();
HashMap<String, Parking> parkings = new HashMap<String, Parking>();
for (DataSnapshot parking :
parkingsData) {
parkings.put(parking.getKey(), parking.getValue(Parking.class));
}
return parkings;
}
Is there a way to get the results from the Task in an await fashion ?