I updated my code like Andro wrote about to me:
public class ZiiziiActivity extends Activity {
ProgressDialog pd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pd = new ProgressDialog(ZiiziiActivity.this);
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
if(msg.what==0)
{
pd.dismiss();
}
}
};
Button end = (Button) findViewById(R.id.button2);
end.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for (int i=0;i<1000000;i++)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //To denote a delay in background processing
}
handler.sendEmptyMessage(0);
}
}); t.start();
}
});
}
}
But when the progress start, it never ends.
What can be wrong?
This is so simple. The basic fact behind this is as follows.
Your progress dialog runs in the main UI. Your
forloop here gets executed so soon and takes more priority and hence you are not able to see your progress dialog but the fact is, your code works fine and progress dialog does show up for fraction of seconds which the human eye can’t catch.Usually people use a progress dialog when they do something in the background thread and not the main thread. So you will have to change a little bit of your code. They are,
1) Surround your
forloop with a thread like this,2) Now add a handler to your onCreate() like this:
Note that you can’t update your UI from a background thread. So in order to update the UI from some other worker thread you go for handlers. So once your for loop gets completed, a call will be made to handlers which updates the UI. (In this case it cancels the progress dialog).