BonnY Dutt BonnY Dutt - 13 days ago 6
Android Question

how to start an activity which displays a UI screen to user while data is loaded in the main activity layout

I am trying to load some data in the main activity layout from the database, while this happens I want to show the user a dialog in the popup. I have tried using thread and also async task but still the screen freezes while the data is being loaded and finally when it completes then it displays my popup. I want the dialog to display simultaneously with data load.
below is the function from main activity that loads the data and calls the async task.

public void call_itemdisplay(final String bookid)
{
new waitAsync().execute();
//load data from DB below
}


The async task that starts a new activity

public class waitAsync extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
Intent i = new Intent(MainActivity.mCon, waitActivity.class);
MainActivity.mCon.startActivity(i);

} catch (Exception e) {
e.printStackTrace();
}
return null;
}


}


The Popup Activity that is started by the async task

public class waitActivity extends Activity {
static waitActivity wact;
public static Context wcon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wact=this;

setContentView(R.layout.activity_wait);
}

}


Need help in showing the POPup activity in the UI while data loads in the main activity. Currently the screen freezes while loading data and then show all together after loading is complete

Answer

In your AsyncTask,

  • Use onPreExecute to show progress dialog
  • Load data in doInBackground, this method will be called on worker thread
  • Hide dialog in onPostExecute

    ... AsyncTask<String, String, String>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // show dialog
            }
        // UPDATE
        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
           // this method will be called when you call
          //  publishProgress from doInBackground.
        }       
            @Override
            protected String doInBackground(String[] params) {
                // load data and return
               // this data will passed to onPostExecute
                publishProgress(param); // call onProgressUpdate
                return null;
            }
    
            @Override
            protected void onPostExecute(String o) {
                super.onPostExecute(o);
                // hide dialog
            }
    }
    

Here are few links, you can find useful in achieving your goal

Comments