Akshay J Akshay J - 2 months ago 42
Android Question

wait for AsyncTask to finish

In the OnCreate method, I have invoked 3 AsyncTask which basically fills data for the 3 Spinners. What I need is that I should have the Login button disabled till all 3 tasks finish. How can I achieve that ?

new SpinnerDataFetcher("GetFreeDrivers1",(Spinner)findViewById(R.id.Spinner_1)).execute();

new SpinnerDataFetcher("GetFreeDrivers2",(Spinner)findViewById(R.id.Spinner_2)).execute();

new SpinnerDataFetcher("GetFreeDrivers3",(Spinner)findViewById(R.id.Spinner_3)).execute();

Answer

Just increment a number that corresponds on how many AsyncTask are done.

        int s = 0;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            new SpinnerDataFetcher(){
               @Override
                protected void onPostExecute(....) {
                   super.onPostExecute(...);
                   s++;
                   check();
                }

            }.execute(); 

            new SpinnerDataFetcher(){
               @Override
                protected void onPostExecute(....) {
                   super.onPostExecute(...);
                   s++;
                   check();
                }

            }.execute(); 

            new SpinnerDataFetcher(){
               @Override
                protected void onPostExecute(....) {
                   super.onPostExecute(...);
                   s++;
                   check();
                }

            }.execute(); 

        }

        public void check(){
          if(s >=3){
             s= 0;
            // enable button here
          }
        }