0
public String retrive(DatabaseReference myRef,String Tag) {         
     myRef = myRef.child(Tag);
     myRef1=myRef;
     String [] Value = new String[1];
     myRef1.addValueEventListener(new ValueEventListener() {
         @Override             public void onDataChange(DataSnapshot dataSnapshot) {
             Value[0] = dataSnapshot.getValue(String.class).toString();
          }
          @Override             public void onCancelled(DatabaseError databaseError) {
          }
      });
     return Value[0];
 }

In this above code, I want to get the updated value of the variable value[0] but the function returns NULL before the EventListener updates the value of the variable.

  • I've encounter so many question like this, here is [my latest answer](http://stackoverflow.com/a/42695655/4112725) to help you out – koceeng Mar 11 '17 at 07:55
  • Possible duplicate of [Android - Return boolean value relative Firebase](http://stackoverflow.com/questions/42690851/android-return-boolean-value-relative-firebase) – koceeng Mar 11 '17 at 07:57
  • I didn't get solution from your above links if you have any answers plz help me – dhrumit patel Mar 11 '17 at 08:45
  • Please take your time to try understand it, because it is almost exact same case. The only different is it use `boolean` while you use `String` – koceeng Mar 11 '17 at 08:47

1 Answers1

0

You can not do it like this. There is another way of doing this which is a better way imo. Change your function like this:

  • Make it return void
  • Add another parameter of type ValueEventListener
  • Pass the event listener wherever you call this method

Changed function:

public String retrive(DatabaseReference myRef,String Tag, ValueEventListener listener) {         
         myRef = myRef.child(Tag);
         myRef1=myRef;
         myRef1.addValueEventListener(listener);
     }

After that when you want to call your function to get the value you may replace the code (which I assume you wrote) from:

String value = retrive(ref, tag);

To:

String value; // this is a field in your class
...
retrive(ref, tag, new ValueEventListener() {
             @Override             public void onDataChange(DataSnapshot dataSnapshot) {
                 value = dataSnapshot.getValue(String.class).toString();
                 doSomethingWithValue(value); // you pass the value to another method and access it in that method
              }
              @Override             public void onCancelled(DatabaseError databaseError) {
              }
          }};

Then you define a method to access that value after it has been assigned with the value:

public void doSomethingWithValue(String value) {
    //here you access the value after it has been assigned
}
Saeed Entezari
  • 3,685
  • 2
  • 19
  • 40