0

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;
    }
Noussa
  • 520
  • 1
  • 4
  • 14

1 Answers1

0

This made an error: "cannot return a value from a method of void result type".

You can't return any value since the type is void.

Edit

You may create a method inside onDataChange() and pass the driver object as parameter.

Log.i("getOneAvailableDriver", driver.toString());
myMethod(driver) // add new function here
return driver; //here where I tried the second time

If you want to know more, you can refer to this post

John Joe
  • 12,412
  • 16
  • 70
  • 135