Search code examples
javaandroidloopsandroid-asynctasksplash-screen

infinite while loop, while AsyncTask is not finish


I have a SplashScreen Activity which call Asynctask Class to get information in internet.

I want to wait while my Asynctask is not finish (time during on internet speed connection)

My activity:

public static boolean test = true;

[...]

final Liste en_ce_moment = new Liste("En ce moment au cinéma", nowMovie);
mesListes.add(en_ce_moment);

//call my Asynctask file 
fetchNowMovie process = new fetchNowMovie();
process.execute();

while(test)
{

}

Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(i);

My Asynctask:

protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        SplashScreenActivity.test = false;

        SplashScreenActivity.nowMovie.clear();
        SplashScreenActivity.nowMovie.addAll(list);

    }

Logically, the boolean became false in onPostExecute so the while loop stop and the intent have to start but the while loop never stop...


Solution

  • Let's do what you want to do in a safe way by using simple interface logic:

    So we added our simple interface and we re-define your MyAsnycTask class's constructor like so:

    public class MyAsnycTask extends AsyncTask
    {
    
        OnTaskFinished listener;
    
        // Our simple interface
        public interface OnTaskFinished {
            void TimeToNextActivity();
        }
    
        // Your MyAsnycTask class constructor
        public MyAsnycTask(OnTaskFinished l) {
            listener = l;
        }
    
        . . .
    
    

    As a last line of code in onPostExecute(), we're done whatever we're doing. So tell this via our listener:

    listener.TimeToNextActivity();
    

    To use our interface that we added earlier, your Activity must implements it. So we implements it. And in implemented method, we go to next Activity with Intent:

    public class MyActivity extends Activity
    implements MyAsnycTask.OnTaskFinished
    {
    
        @Override
        public void TimeToNextActivity()
        {
            // Here go to next activity
            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
    
        }
    

    As we modified our MyAsnycTask class's constructor, we must initialize it like this:

    MyAsnycTask process = new MyAsnycTask(this);
    process.execute();