By Ilya Cucumber


2017-12-16 16:25:28 8 Comments

I don't have much experience with Java. I'm not sure if this question is stupid, but I need to get a user name from Firebase realtime database and return this name as a result of this method. So, I figured out how to get this value, but I don't understand how to return it as result of this method. What's the best way to do this?

private String getUserName(String uid) {
    databaseReference.child(String.format("users/%s/name", uid))
            .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // How to return this value?
            dataSnapshot.getValue(String.class);
        }

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

4 comments

@DragonFire 2019-04-18 08:02:36

This is working, you can use the values from a datasnapshot outside onDataChange by passing the value as a paramter to another function, please see my answer below it is working and I am using it all over the place in my app.

// Get Your Value
private void getValue() {

    fbDbRefRoot.child("fbValue").addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            String yourValue = (String) dataSnapshot.getValue();
            useValue(yourValue);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

// Use Your Value
private void useValue(String yourValue) {

    Log.d(TAG, "countryNameCode: " + yourValue);

}

The main difference between mine and Rbar's answer is that I am passing the value as a paramter to a function and then using it.

@klaid bendio Moran 2018-08-01 13:08:33

Here's a crazy Idea, inside onDataChange, put it inside a TextView with visibility gone textview.setVisiblity(Gone) or something, then do something like

textview.setText(dataSnapshot.getValue(String.class))

then later get it with textview.getText().toString()

just a crazy simple Idea.

@Alex Mamo 2017-12-17 09:26:23

This is a classic issue with asynchronous web APIs. You cannot return something now that hasn't been loaded yet. With other words, you cannot simply create a global variable and use it outside onDataChange() method because it will always be null. This is happening because onDataChange() method is called asynchronous. Depending on your connection speed and the state, it may take from a few hundred milliseconds to a few seconds before that data is available.

But not only Firebase Realtime Database loads data asynchronously, almost all of modern other web APIs do, since it may take some time. So instead of waiting for the data (which can lead to unresponsive application dialogs for your users), your main application code continues while the data is loaded on a secondary thread. Then when the data is available, your onDataChange() method is called and can use the data. With other words, by the time onDataChange() method is called your data is not loaded yet.

Let's take an example, by placing a few log statements in the code, to see more clearly what's going on.

private String getUserName(String uid) {
    Log.d("TAG", "Before attaching the listener!");
    databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // How to return this value?
            dataSnapshot.getValue(String.class);
            Log.d("TAG", "Inside onDataChange() method!");
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
    Log.d("TAG", "After attaching the listener!");
}

If we run this code will, the output wil be:

Before attaching the listener!

After attaching the listener!

Inside onDataChange() method!

This is probably not what you expected, but it explains precisely why your data is null when returning it.

The initial response for most developers is to try and "fix" this asynchronous behavior, which I personally recommend against this. The web is asynchronous, and the sooner you accept that, the sooner you can learn how to become productive with modern web APIs.

I've found it easiest to reframe problems for this asynchronous paradigm. Instead of saying "First get the data, then log it", I frame the problem as "Start to get data. When the data is loaded, log it". This means that any code that requires the data must be inside onDataChange() method or called from inside there, like this:

databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // How to return this value?
        if(dataSnapshot != null) {
            System.out.println(dataSnapshot.getValue(String.class));
        }
    }

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

If you want to use that outside, there is another approach. You need to create your own callback to wait for Firebase to return you the data. To achieve this, first you need to create an interface like this:

public interface MyCallback {
    void onCallback(String value);
}

Then you need to create a method that is actually getting the data from the database. This method should look like this:

public void readData(MyCallback myCallback) {
    databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String value = dataSnapshot.getValue(String.class);
            myCallback.onCallback(value);
        }

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

In the end just simply call readData() method and pass an instance of the MyCallback interface as an argument wherever you need it like this:

readData(new MyCallback() {
    @Override
    public void onCallback(String value) {
        Log.d("TAG", value);
    }
});

This is the only way in which you can use that value outside onDataChange() method. For more information, you can take also a look at this video.

@Peter Haddad 2018-07-31 16:46:14

Can this be achieved using Future interface and Callable? developer.android.com/reference/java/util/concurrent/Future

@Alex Mamo 2018-07-31 18:25:03

Hi Peter! It might work. I didn't tried yet but I will. I don't know if you know this, but here is an interesting article.

@Peter Haddad 2018-07-31 19:43:17

Yes, I saw it before since it is written as a comment in many places. But, I haven't read it, because I know how asynchronous works after reading couple of Q&A here. Anyway, I read it now and I guess it is better not to use Future since we need to use newSingleThreadExecutor() that creates another thread, and since the api is asychronous then it is already in a thread in java and we have to maintain this thread also and write more code.

@Alex Mamo 2018-07-31 20:24:13

@PeterHaddad Firebase client already runs all network operations in a background thread so I think you are right. There is no need for that. Thanks for providing me that resource!

@DragonFire 2019-04-18 08:06:40

@PeterHaddad just pass the value as a parameter, see my answer below...

@Alex Mamo 2019-04-18 08:26:45

@DragonFire You are just pasing yourValue as a parameter, you are not witing for the data.

@Rbar 2017-12-17 03:19:13

I believe I understand what you are asking. Although you say you want to "return" it (per se) from the fetch method, it may suffice to say you actually just want to be able to use the value retrieved after your fetch has completed. If so, this is what you need to do:

  1. Create a variable at the top of your class
  2. Retrieve your value (which you have done mostly correctly)
  3. Set the public variable in your class equal to value retrieved

Once your fetch succeeds, you could do many things with the variable. 4a and 4b are some simple examples:

4a. Edit: As an example of use, you can trigger whatever else you need to run in your class that uses yourNameVariable (and you can be sure it yourNameVariable not null)

4b. Edit: As an example of use, you can use the variable in a function that is triggered by a button's onClickListener.


Try this.

// 1. Create a variable at the top of your class
private String yourNameVariable;

// 2. Retrieve your value (which you have done mostly correctly)
private void getUserName(String uid) {
    databaseReference.child(String.format("users/%s/name", uid))
            .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // 3. Set the public variable in your class equal to value retrieved
            yourNameVariable = dataSnapshot.getValue(String.class);
            // 4a. EDIT: now that your fetch succeeded, you can trigger whatever else you need to run in your class that uses `yourNameVariable`, and you can be sure `yourNameVariable` is not null.
            sayHiToMe();
        }

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

// (part of step 4a)
public void sayHiToMe() {
  Log.d(TAG, "hi there, " + yourNameVariable);
}

// 4b. use the variable in a function triggered by the onClickListener of a button.
public void helloButtonWasPressed() {
  if (yourNameVariable != null) {
    Log.d(TAG, "hi there, " + yourNameVariable);
  }
}

Then, you can use yourNameVariable wherever you would like throughout your class.


Note: just be sure you check that yourNameVariable is not null when using it since onDataChange is asynchronous and may not have completed at the time you attempt to use it elsewhere.

@Alex Mamo 2017-12-17 09:32:20

This is an incorrect answer. This is not how thing are going on when it comes to asynchronous methods. Using this answer you'll have your variable yourNameVariable to be always null when using "wherever you would like throughout your class". You can use it only in your onDataChange() method. That's it.

@Rbar 2017-12-17 19:08:23

@AlexMamo, your solution of defining an interface works nicely, but the following part of your comment is incorrect: "yourNameVariable to be always null." For those looking for a more lightweight solution (that does not require defining an interface) this works well. Once the variable has been retrieved and set, they can trigger any functions that need the result and know that the variable is not null (as long as it exists on firebase in the first place). I have updated my example so you can see a concrete use-case.

@Alex Mamo 2017-12-18 08:00:59

Furthermore calling that method has nothing to do with asynchronous behaviour of methods. Calling that method is the same as using this line Log.d(TAG, "hi there, " + yourNameVariable); inside onDataChange() method. This means that when onDataChange() method is triggered you are calling that method.

@Rbar 2017-12-18 18:47:20

@AlexMamo, the function was merely a single example. You can do many other things that do not automatically trigger a funciton. For another simple example, a button could be visible once the data has loaded and triggering the button would do something with the data you have fetched. Again, your example is nice and I am not arguing that it shouldn't be the accepted answer. That being said, your blanket statement (even the full one) of yourNameVariable will be be always null when using "wherever you would like throughout your class". is not true for all cases ... (continued)

@Rbar 2017-12-18 18:47:27

There are several cases in which you could use the value retrieved outside of fetching the data. My point is merely that there is more than one way to skin a cat; some lighter solutions like the one I have posted may work better for some people, and your may work better for many others. No need to get worked up, just sharing knowledge here.

@Alex Mamo 2017-12-18 19:57:36

A button can be visible once the data has is loaded only if you set the visibility of that button inside onDataChange() or if you use your own callback to wait for Firebase to return you the data. The second example is the same as the first one. Calling a method from within a method is the same as having the body of that method inside onDataChange(). This has nothing to do with the asynchronous concept.

@Alex Mamo 2017-12-18 19:57:38

There are no cases in which you can use the value retrieved outside other that i already mentioned in my answer. You cannot return something now that hasn't been loaded yet. Your solution isn't a lighter one, won't work at all. Try to use the log statements and you'll understand what i mean.

@DragonFire 2019-04-18 08:03:59

@AlexMamo please see my answer below stackoverflow.com/a/55741593/3904109 it can be done...

@Alex Mamo 2019-04-18 08:27:42

@DragonFire As I already commended there, you don't wait for the data you just simply pass that object as a parameter.

Related Questions

Sponsored Content

60 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

63 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3764003 View
  • 3185 Score
  • 63 Answer
  • Tags:   java random integer

25 Answered Questions

[SOLVED] How to get an enum value from a string value in Java?

  • 2009-03-02 22:56:34
  • Malachi
  • 969154 View
  • 1781 Score
  • 25 Answer
  • Tags:   java enums

25 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1764630 View
  • 2063 Score
  • 25 Answer
  • Tags:   java arrays

79 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

51 Answered Questions

[SOLVED] How do I fix android.os.NetworkOnMainThreadException?

9 Answered Questions

[SOLVED] Why is subtracting these two times (in 1927) giving a strange result?

  • 2011-07-27 08:15:58
  • Freewind
  • 594165 View
  • 6392 Score
  • 9 Answer
  • Tags:   java date timezone

77 Answered Questions

3 Answered Questions

Sponsored Content