Reputation: 4089
I want to display a dialog window after execution of a work, AND progress dialog should be displayed untill the work is finished.so i try to use thread in following code.
ProgressDialog dialog=new ProgressDialog(SampActivity.this);
dialog.setMessage("Please wait..");
dialog.setProgress(100);
dialog.setMax(5000);
dialog.show();
Thread progressing = new Thread()
{
@Override
public void run()
{
try
{
Thread.sleep(5000);
Looper.prepare();
AlertDialog.Builder
alertDialogBuilder = new AlertDialog.Builder(SampActivity.this);
alertDialogBuilder.setMessage("finished");
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
catch (Exception e)
{
e.printStackTrace();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SampActivity.this);
alertDialogBuilder.setMessage("Unable to stop SAP.The connection is down.Please retry after sometime.");
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
finally
{
dialog.dismiss();
}
runOnUiThread(new Runnable(){
@Override
public void run() {
if(dialog.isShowing())
dialog.dismiss();
}
});
}
};
progressing.setPriority(Thread.MAX_PRIORITY );
progressing.start();
after running this program the program hangs.i dont know whats wrong in the code. Please help me to figure it out. Thanks in advance.
Upvotes: 0
Views: 1072
Reputation: 15973
You cannot update the ui from non-ui thread...You can or use runOnUiThread
to do the part that updates the ui:
runOnUiThread(new Runnable() {
public void run() {
//display dialog
}
});
Or better use an AsyncTask
..
private class MyTask extends AsyncTask<URL, Integer, Long> {
private Context context;
public MyTask(Context context) {
this.context = context;
}
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", "msg", true);
}
protected Long doInBackground(URL... urls) {
//do something
}
protected void onPostExecute(Long result) {
progressDialog.dismiss();
}
}
Upvotes: 2