Skip to content Skip to sidebar Skip to footer

Need Help In Showing The Popup Dialog In The Ui While Data Loads In Background Async Task

I have a progress dialog in onPreExecute method of an async task but it doesn't show immediately while the async task fetches data from the DB. Can you suggest something that will

Solution 1:

You don't need a loop like this after async task. It will block your UI thread.

while(MainActivity.flag==0) // wrong - blocking main thread
            {
                c++;
            }

You need to create a method in activity, say onDataAvailable and in this method you can do whatever you want to do, either go to next activity or whatever, then call this method from onPostExecute

@OverrideprotectedvoidonPostExecute(String s) {
        super.onPostExecute(s);
        processingDialog.dismiss();
      //  call load complete method here


    }

Here is your updated async task.

publicclassWaitAsyncTaskextendsAsyncTask<String, Void, String> {

    privateWeakReference<MainActivity> activityRef;

    publicWaitAsyncTask(MainActivity activity){
        activityRef = newWeakReference<MainActivity>(activity);
    }

     @OverrideprotectedvoidonPreExecute() {
        super.onPreExecute();
        // show dialog
    }
    @OverrideprotectedStringdoInBackground(String... params) {
        // do you work in backgroundreturnnull;
    }

    @OverrideprotectedvoidonPostExecute(String data) {
        super.onPostExecute(data);
        // hide dialogif(activityRef.get() != null){
            // call load completed method in activity
            activityRef.get().loadCompleted(data);
        }
    }
} // WaitAsyncTask

And in your MainActivity, create a method in which you want to receive results. I have create this method

publicvoidloadCompleted(String data){
        // this will be called automatically after fetching data is completed
    }

in MainActivity which I am calling from my task. You don't need while loop to wait. This method will be called after your data is fetched.

Solution 2:

Pass activity context to async task through a constructor in asynctask and use that context instead. like

Context mainActivityCtxt;  
     waitAsync(Context ctx) {
         this.mainActivityCtxt = ctx;
     };  

     newwaitAsync(mainActivityCtxt).execute(SQL); 

Hope this helps.

Post a Comment for "Need Help In Showing The Popup Dialog In The Ui While Data Loads In Background Async Task"