I’m using a thread so that I can show a progress dialog while my app loads some data. If there is an error it will stop the progress dialog and show the popup saying “error”. However I found out that alert dialogs cannot run inside a UI thread and that I need to use a Handler. Can someone with help with this issue? Here is my code. Thanks
verifyCode.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final ProgressDialog progressDialog = ProgressDialog.show(
Activate.this, "", "Loading...");
new Thread(new Runnable() {
public void run() {
try {
new AlertDialog.Builder(Activate.this)
.setTitle(getResources().getString(R.string.InvalidKey))
.setMessage(getResources().getString(
R.string.PleaseEntervalidRegistration)).setNeutralButton(
"OK", null).show();
progressDialog.dismiss();
//more code
}).start();
}
You can’t make changes to UI element on non-UI threads.
onClickwill run on the UI thread, but since you spawn aThreadinsideonClickthen non-UI elements cannot be manipulated from inside thatThread. Move yourAlertDialogandProgressDialogcalls to just prior to spawning the newThread.Also, as @lightblade suggested, If you need to do some sort of action which requires heavy background processing and UI manipulation based on that processing, then you should use
AsyncTasks. It provides methods you can override for pre-processing, actual processing, post-processing, and updating progress.