In my Activity, I load the content for a list from a DB, and want to display a ProgressDialog while it′s loading.
I got both working on it′s own, but if I load the data in a thread (which I should do?), the list is displayed before it′s data is loaded. But if I use join, the ProgressDialog doesnt even appear.
How can I combine this? Or is this not possible at all with threads? (AsyncTask maybe?)
Here′s the code for reference:
final ProgressDialog progressD=ProgressDialog.show(ShopSwitchActivity.this, "", "Loading..", true);
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
try
{
getData();
}catch(Exception e){}
}
});
myThread.start();
try {
myThread.join();
} catch (InterruptedException e) {
}
progressD.dismiss();
EDIT: Updated Code with AsyncTask:
public class LoadList extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
ShopSwitchActivity activity;
public LoadList(ShopSwitchActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Boolean doInBackground(final String... args) {
try{
activity.getData();
} catch (Exception e) {
Log.e("error", e.getMessage());
}
return true;
}
}
Edit: My Solution
Using AsyncTask now to load the Data, and after it′s done, I refresh the list with the new data.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…