0

I have a method that reads some data from the firebase database.
Let's call it getMyData() I am attaching a firebaseQuery.addListenerForSingleValueEvent(new ValueEventListener() {....

My code structure is something like this. SomeDataType myData = getMyData(); if(myData==someCondition){//some logic} else{//some logic}

The problem is that the event listener doesn't get fired until my code has passed.

So something like this happens SomeDataType = null and it goes to my where clause. firebase uses events so it's not linear code execution but I am a little confused... Can you help me?

johny
  • 1
  • `addListenerForSingleValueEvent` is asynchronous. That's the way it works. It's not going to block your app to wait for the results of the query, which could take any amount of time. https://medium.com/google-developers/why-are-the-firebase-apis-asynchronous-e037a6654a93 – Doug Stevenson May 08 '18 at 18:06
  • @DougStevenson any idea how to approach my problem? – johny May 08 '18 at 18:07
  • You'll have to learn asynchronous programming techniques and apply that to the use of Firebase APIs. I'll suggest doing the Firebase Android codelab to get some experience. – Doug Stevenson May 08 '18 at 18:12
  • @DougStevenson ok I understand that it is async... anyway how would you approach this problem... You need some data that you have to use further for the business logic. You have to fetch it ofc. – johny May 08 '18 at 18:14
  • Check my answer from this [post](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774). – Alex Mamo May 08 '18 at 18:14
  • @AlexMamo your post was pretty good, anyway what if my callback must accept an argument? – johny May 08 '18 at 18:39
  • There will be no problem. Add a another argument, will work fine. – Alex Mamo May 08 '18 at 18:44
  • @AlexMamo in other words from where do I pass the "String value"? – johny May 08 '18 at 18:45
  • @AlexMamo oh sorry my mistake... anyway thanks. U deserve an upvote – johny May 08 '18 at 19:06

0 Answers0