0

I'm having hard times with building my app that uses Firebase Realtime Database.

What I want to achieve:

I have two tables:

GuessedSongsTable

SongsTable

I want to get 10 songs that have not been guessed by current User yet.

I thought about method similar to that (pseudo-code) running in my Activity:

public List<SongPOJO> getTenUniqueSongs() {
    List<SongPOJO> myList = new ArrayList<>();
    int songId = 0;

    while(myList.size() < 10) {

        SongPOJO mySong = getASongFromTheDatabase(songId);

        if (!checkIfSongExistsInTableGuessedSongs())
            myList.add(mySong);

        ++songId;
    }
} 

I know how to write request to the Realtime database's reference (get dataSnapshot and check if dataSnapshot exists using exists() method). But that's not the case.

The problem is that I want to get this data synchronously in the main Thread (I will give the user some kind of waiting alert until this operation finishes successfully). But I don't know how to do that.

I've done some research and I was trying to implement this solution: https://stackoverflow.com/a/45308259/5834189 using TaskCompletionSource . But the thing is it cannot be run in the main Thread. I know I can handle this using AsyncTask but I have no idea how to get the data synchronously.

I completely understand that working with the database means making asynchronous calls, but how to get data in a specific moment?

Could you please help me with finding the solution? Multithreading seems to be really mysterious to me at the moment.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Wojtek Smol
  • 57
  • 1
  • 2
  • There is no way to retrieve data synchronously with the Firebase SDK. You could retrieve the data using the REST API and make that a blocking call, but I doubt you want to do that either. It sounds more like you want to show a "please wait" indicator, that you then hide once the data has loaded. – Frank van Puffelen Dec 12 '18 at 17:44
  • Why don't you use asyntask to get the data, and just call asynTaskObj.get() inside your UI thread? The get() method will block until asynctask finishes. – Steven Dec 12 '18 at 17:56
  • @Steven The Firebase Database client, already runs all network operations in a background thread. This means that all operations take place without blocking your main thread. Putting it in an AsyncTask does not give any additional benefits. If you are using `FirebaseRecyclerAdapter`, you can override the `onDataChanged()` method and hide the `ProgressBar` inside it. – Alex Mamo Dec 12 '18 at 17:57
  • @Alex Mamo Ah I see. I haven't used Firebase myself yet. Thanks for the info. – Steven Dec 12 '18 at 17:58
  • @Steven You're welcome. – Alex Mamo Dec 12 '18 at 17:58
  • But can't I do it somehow using Callable and Future? – Wojtek Smol Dec 12 '18 at 18:13

0 Answers0