Danny Buonocore
Danny Buonocore

Reputation: 3777

Updating UI during AsyncTask

How can I edit the views of an activity from an AsyncTask BEFORE the task is complete? I cannot access any of the views from the doInBackground method, and I do not want to wait until the task has completed. Is there a way to go about doing this? Or do I have to create a thread within the doInBackground (which sounds to me would be bad practice) and then access the view on that thread's completion?

Upvotes: 0

Views: 110

Answers (4)

Itzik Samara
Itzik Samara

Reputation: 2288

Override this method:

protected void onProgressUpdate(Integer... progress) {
    setProgressPercent(progress[0]);
}

Call it in doInBackground() of your AsyncTask. This method publishProgress(Progress... values)

happens on the UI thread when you call it from doInBackground().

For more information, read AsyncTask

Upvotes: 1

Zafer Celaloglu
Zafer Celaloglu

Reputation: 1418

You need to override this method inside your AsynTask Class:

  @Override
            protected void onProgressUpdate(Void... values) {
                // TODO Auto-generated method stub
                ProgressBar bar = (ProgressBar) findViewById(R.id.prgLoading); 
                bar.setIndeterminate(true);
                super.onProgressUpdate(values);
            }

You can define a progress bar as I show in here and set some value into it.

Upvotes: 1

Jithu
Jithu

Reputation: 1478

You can update the UI from onProgressUpdate(). There is a tricky way, you can send some integer or boolean value to progress update and change your UI according to the condition.

@Override
        protected void onProgressUpdate(Integer... values) {
            if(values[0] == 1) {
          //    update the UI
                button.settext("updating");
            }
        }

You can call onProgressUpdate fram asynctask by calling

publishProgress(1);

Hope this works, try out.

Upvotes: 1

user2768
user2768

Reputation: 824

You could define the class MyAsyncTask containing the following:

private final ProgressDialog progressDialog;

public MyAsyncTask(Context context) {
    super(context);

    progressDialog = new ProgressDialog(context);
    progressDialog.setTitle(R.string.title);
    progressDialog.setButton(
        DialogInterface.BUTTON_NEGATIVE,
        context.getResources().getString(R.string.abort), 
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MyAsyncTask.this.cancel(true);
                progressDialog.dismiss();
            }
        }
    ); 
    progressDialog.show();
}

@Override
protected void onProgressUpdate(String... params) {
    progressDialog.setMessage(params[0]);
}

You can then use the ProgressDialog to report back to the GUI, e.g., by calling publishProgress("TEST").

Upvotes: 1

Related Questions