I love coding
I love coding

Reputation: 1191

How to use progress dialog with AsyncTask and fragment?

I want to use a ProgressDialog within a Fragment for an AsyncTask. With Activity the following code works perfectly, but with Fragment no.

public class ResultTask extends AsyncTask<String, Void, Report> {

    private ProgressDialog pDialog;
    private Context context;

    public ResultTask(Context context) {
        super();
        this.context = context;

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Loading...");

        pDialog.show();
    }

    @Override
    protected Report doInBackground(String... params) {
      //myLong operation

    }

    @Override
    protected void onPostExecute(Report report) {
        pDialog.dismiss();
        super.onPostExecute(report);
    }

}

How Can I fix in a very simple way ? The idea of the ProgressBar, is just to let understand the user, that a long operation is processed.

UPDATE

Here is the code of the Fragment, where I execute the AsyncTask:

ResultTask task = new ResultTask(getActivity());
Report report = task.execute("paramenters").get();

And this is the code of the Activity, where I select the Fragment:

private void changeActivity(Button button, final Fragment fragment) {
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, fragment).commit();
            }
        });

    }

Upvotes: 0

Views: 2195

Answers (1)

narancs
narancs

Reputation: 5294

If you use .get() for an AsyncTask than it is going to WAIT there until the result not arriving, which case the UI thread to be blokced, while task is running. USE .execute and use handlers to communicate with the task. In this case, you don`t need a handler, because the onPre and onPost methods are related the UI, but the doInBackGround not :)

http://developer.android.com/reference/android/os/AsyncTask.html#get()

article: http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

Upvotes: 1

Related Questions