0

I'm interested in fetching 3 JSONs from the server on the splash screen of my app, so the user doesn't sit and see a loading spinner.

Currently, I'm doing it like this:

    MainActivity.raffle_controller.fetch_current_raffles(this);

    startActivity(new Intent(this, MainActivity.class));
    finish();

In the Controller, I'm populating an ArrayList on success from the JSON received. (using Volley)

But the request runs async, so my MainActivity loads with an empty screen.

After reloading the fragment though, everything from the controller is displayed.

I am curious if I can somehow wait for the list to be populate, then display the fragment.

Majid Ahmadi Jebeli
  • 517
  • 1
  • 6
  • 22
Dorinel Panaite
  • 492
  • 1
  • 6
  • 15

2 Answers2

1

I am answering this just because I want to help and I don't have enough reputation to leave a comment.

If you are dealing with async tasks, you should get used to use listeners. I did not fully understand your question but I think you may find your answer in here.

0

You can add a callback to fetch_current_rafles

You will have something like that:

public void fetch_current_raffles(Activity activity, Runnable callback){

...
@Override
public void onResponse(JSONObject response) {
    mTxtDisplay.setText("Response: " + response.toString());
    callback.run();
}
...
}

In your splash, you will do:

MainActivity.raffle_controller.fetch_current_raffles(this, 
new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(this, MainActivity.class));
                    finish();
                }
            }
);

If you use Java8, it is more expressive

MainActivity.raffle_controller.fetch_current_raffles(this,
()->{
       startActivity(new Intent(this, MainActivity.class));
       finish(); 
    });

But If you want to avoid such a callback syntax, you can use some library with RxJava. I strongly advise retrofit. But you can also use RxVolley

maheryhaja
  • 1,617
  • 11
  • 18
  • is it bad to use callback? Also, I have 3 calls to do, how can I implement the callback to do the startActivity after all 3 have finished? – Dorinel Panaite Jan 06 '18 at 21:08
  • can I use a timeout or something if data can't be fetched? – Dorinel Panaite Jan 06 '18 at 21:39
  • this [question](https://stackoverflow.com/questions/25098066/what-is-callback-hell-and-how-and-why-rx-solves-it) about callback hell will help you to understand why it is bad habit to use callback. With 3 calls, you will certainly dive into an unmaintainable and very complicated code. RxJava is a really good alternative to avoid that. So far, if your project is really urgent you can manage with callbacks and Threads. this [article](https://www.journaldev.com/1024/java-thread-join-example) will help you – maheryhaja Jan 07 '18 at 18:28