How to use ProgressDialog to show background progress in android
-
19-02-2021 - |
Question
to show a background process i used ProgressDialogBox
.
My code is as
add_button.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam) {
progressDialog = ProgressDialog.show(AddTicketActivity.this, "", "Loading...");
new Thread() {
public void run() {
try{
sleep(10000);
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
progressDialog.dismiss();
}
}.start();
Its working fine. But the problem is progess shows for 10000 ms where as i want it to show untill my data is fetched/added. i mean it should be dependent on fetching/adding time.
i thought to do like it
public void onClick(View viewParam) {
progressDialog = ProgressDialog.show(AddTicketActivity.this, "", "Loading...");
Fetching data code here
progressDialog.dismiss();
}
But it dint work, does not show any progress bar.
How can i use it.
Thanks.
Solution
Well your code is fine :
public void onClick(View viewParam) {
progressDialog = ProgressDialog.show(AddTicketActivity.this, "", "Loading...");
// Fetching data code here
// ...
// Data Fetched
progressDialog.dismiss();
}
This should work, as long as your are fetching the code in the same thread (although that might lead to an ANR. Consider using AsyncTask
).
EDIT : Note that if you are fetching data in a separate thread, according to your logic you will show your progress dialog and then immediately close it.
OTHER TIPS
This way of progress bar is asynchronous. This might be helpful for u.
// class for displaying dialog box
class DialogTask extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... urls) {
return null;
}
@Override
protected void onPostExecute(String result) {
method to execute
super.onPostExecute(result);
}
}
I would suggest you to use AsyncTask with either ProgressDialog or ProgressBar.
- In onPreExecute() method, display the ProgressBar or make it visible again like:
progressbar.setVisibility(View.VISIBLE);
- In doInBackground() method, perform the background task
- In onPostExecute() method, just hide the ProgressBar using the
progressbar.setVisibility(View.INVISIBLE);