I am new to firebase. I have a method which returns a driver object retrieved from a firebase database. Please help me.
I did research and found that the problem is that onDataChange() is asynchronous so it is called last. So I tried to put the final return statement in the onDataChange(). This made an error: "cannot return a value from a method of void result type". Some solution suggested to save the return type in a variable and return it at the end, but this solution was for primitive data types which is not my case.
private Driver getOneAvailableDriver(String driverUid) {
//get the driver's uid code in the available drivers node
final DatabaseReference driverUidRef = FirebaseDatabase.getInstance().getReference(getString(R.string.drivers_available))
.child(driverUid);
final Driver driver = new Driver();
//get the driver's track
driverUidRef.child(getString(R.string.track)).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String track = dataSnapshot.getValue(String.class);
driver.setTrack(track);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//get the driver's location
DatabaseReference locationRef = driverUidRef.child("l");
locationRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ArrayList<Double> customLocation = (ArrayList<Double>) dataSnapshot.getValue();
LatLng location = new LatLng(customLocation.get(0), customLocation.get(1));
driver.setLocation(location);
Log.i("getOneAvailableDriver", driver.toString());
return driver; //here where I tried the second time
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Log.i("getOneAvailableDriver", driver.toString());
return driver;
}