How can I read values from Firebase Realtime Database by using a Java method in AndroidStudio?

Viewed 892

My Firebase Realtime Database has been built by loading an object of the Java class HashMap. In my Android Studio app I'm trying to write a method that takes a String (the key) as input, searches through the database and if the string is found it returns the associated Float (the value), otherwise it returns 0. How can I do this? Any help would be really appreciated!

EDIT: I've tried to follow the suggestions, adapting them to my particular case, but I didn't manage to solve the problem yet.
I wrote the following code in MainActivity:

DatabaseReference myRef;
Float tempValue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    myRef = FirebaseDatabase.getInstance().getReference("myRoot");
    tempValue=0f;
    ...
}

public void retrieveValueFromDatabase(String childName, final MainActivity activity){
    myRef.child(childName).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Float value=dataSnapshot.getValue(Float.class);
            if (value==null){
                value=0f;
            }
            activity.tempValue=value;
            //First Toast
            //Toast.makeText(activity,"tempValue = "+tempValue.toString(), Toast.LENGTH_LONG).show();
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });
}

public void useValues(){
    retrieveValueFromDatabase(childName,this);
    //Second Toast
    //Toast.makeText(this,"tempValue = "+tempValue.toString(), Toast.LENGTH_LONG).show();
    //code using tempValue from here
    ...
}

If I uncomment the first toast, the correct value inside tempValue is shown, but if I uncomment the second toast, the value of tempValue shown is the default one (0.0). What am I missing?

1 Answers

You need to use addValueEventListener to retrieve data from the database:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("myRoot").orderByChild("name").equalTo("peter");
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Log.i("Database", dataSnapshot.child("floatValue").getValue(Long.class));
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
})

Here, you add a reference to the root node, then query using equalTo() to check if name = peter exists in the database and return the float value.

You should read the guide:

https://firebase.google.com/docs/database/android/read-and-write

Related