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();
}
});
}