Reputation: 54949
i am trying to use Alert Dialog Box and Async Task in the activity and am getting the following error
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Code:
public class loginTask extends AsyncTask<Void, Void, Void> {
public ProgressDialog loginDialog = new ProgressDialog(
LoginActivity.this);
@Override
protected void onPreExecute() {
loginDialog.setMessage("Please wait Logging in");
loginDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
if(loginUser()) {
loginDialog.dismiss();
alertbox("title", "winnn", "Okay");
} else {
loginDialog.dismiss();
alertbox("title", "message", "Okay");
}
return null;
}
@Override
protected void onPostExecute(Void unused) {
loginDialog.dismiss();
Intent intentHome = new Intent(LoginActivity.this,
HomeActivity.class);
startActivity(intentHome);
}
}
Upvotes: 1
Views: 5519
Reputation: 128428
You can't update UI inside the doInBackground()
method directly. (Yes if you still want to execute then write the same inside the runOnUiThread()
method inside the doInBackground()
)
Otherwise, do it inside the onPostExecute()
method.
public class loginTask extends AsyncTask<Void, Void, Void>
{
public ProgressDialog loginDialog = new ProgressDialog( LoginActivity.this );
public Boolean flag;
@Override
protected void onPreExecute() {
loginDialog.setMessage("Please wait Logging in");
loginDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
if(loginUser())
flag = true;
else
flag=false;
return null;
}
@Override
protected void onPostExecute(Void unused) {
loginDialog.dismiss();
if(flag)
alertbox("title", "winnn", "Okay");
else
alertbox("title", "message", "Okay");
}
}
Upvotes: 10
Reputation: 399
the onPreexecute and onPostExecute are part of the UI parts in the Async Task.. the doInBackground is a seperate thread so any thing done inside the doInBackground needs to be handled in the form of progressUpdate
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Example Reference: Link
reflects any changes you need to make to the UI inbetween the doInBackground process.
Upvotes: 1