ProgressDialog in a separate thread
16,270
Solution 1
1.show your process dialog in main thread
2.start a new thread (such as Thread A) to process your heavy job
3.when done, use handler to send a message from Thread A to main thread, the latter dismisses the process dialog
code like this private ProcessDialog pd;
private void startDialog()
{
pd = ProgressDialog.show(MainActivity.this, "title", "loading");
//start a new thread to process job
new Thread(new Runnable() {
@Override
public void run() {
//heavy job here
//send message to main thread
handler.sendEmptyMessage(0);
}
}).start();
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
pd.dismiss();
}
};
Solution 2
Try something like this:
private class MyAwesomeAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog mProgress;
@Override
protected void onPreExecute() {
//Create progress dialog here and show it
}
@Override
protected Void doInBackground(Void... params) {
// Execute query here
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//update your listView adapter here
//Dismiss your dialog
}
}
To call it:
new MyAwesomeAsyncTask().execute();
Author by
Alex
Updated on June 26, 2022Comments
-
Alex almost 2 years
I have a procedure that extracts data from a database and populates it to the list. I want to display progress dialog box while query is executed, but it visually appears only after the query is executed. I believe I have to run a
ProgressDialog
in a separate thread, but followed few suggestions and could not make it work.So in my
Activity
I just haveprivate void DisplayAllproductListView(String SqlStatement) { ProgressDialog dialog = ProgressDialog.show(MyActivity.context, "Loading", "Please wait...", true); //.................. //.................. //execute sql query here dialog.dismiss(); }
thanks