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

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


    }

Here is your updated async task.

public class WaitAsyncTask extends AsyncTask<String, Void, String> {

    private WeakReference<MainActivity> activityRef;

    public WaitAsyncTask(MainActivity activity){
        activityRef = new WeakReference<MainActivity>(activity);
    }

     @Override
     protected void onPreExecute() {
        super.onPreExecute();
        // show dialog
    }
    @Override
    protected String doInBackground(String... params) {
        // do you work in background
        return null;
    }

    @Override
    protected void onPostExecute(String data) {
        super.onPostExecute(data);
        // hide dialog
        if(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

  public void loadCompleted(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;
     };  

     new waitAsync(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"