I was trying to show a ProgressDialog in an AsyncTask, but I was getting the error Can't create handler inside thread that has not called Looper.prepare()
.
So I searched for it and found here that someone had this problem before.
I took the second answer you can see in there and implemented my AsyncTask that way. Everything is good now, but I guess there must be some better way to display that dialog.
This it my AsyncTask after I fixed it
private class MyAsyncTask extends AsyncTask<Void, Void, ArrayList</*SomeObject*/>> {
ProgressDialog mDialog;
private MyAsyncTask() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
mDialog = new ProgressDialog(getActivity());
}
});
}
@Override
protected void onPreExecute() {
super.onPreExecute();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mDialog.setMessage("AsyncTask is starting...");
mDialog.show();
}
});
}
@Override
protected ArrayList</*SomeObject*/> doInBackground(Void... params) {
// some non UI related code...
}
@Override
protected void onPostExecute(ArrayList</*SomeObject*/> someObjects) {
super.onPostExecute(exams);
// some code...
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mDialog.dismiss();
}
});
}
}
My questions are
Is there a better way to display the dialog?
Why I get the errors only in this particular AsyncTask? (the code below works well)
I run the AsyncTask you can see below a hundred times and it never crashed, whereas the first one never executed successfully. There must be something I can't see!
private class MyAsyncTask extends AsyncTask<String, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(mContext);
private LoginConnectTask() {
}
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("aMessage");
dialog.show();
}
protected String doInBackground(String... strings) {
return fancyFunction(strings[0], strings[1]);
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
}