I'm trying create a "read" method which will get a value from Firebase (Google server) using android studio (Java) I wrote the code below but the problem that the value[0] always returning "" as a value and not the value from the server. When Im inside the method "onDataChange",the value[0] is equal to the value from the server but outside, its back to the original value. What is wrong with my code? please help
/**
* Return value
*
* @param parent
* @param child
* @param key
* @return
*/
public static String read(String parent, String child, String key) {
final String[] value = {""};
// Get a reference to our posts
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(parent).child(child);
// Attach a listener to read the data at our posts reference
ref.child(key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String str = dataSnapshot.getValue(String.class);
System.out.println(str);
value[0] = str;
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
return value[0];
}
}