我在AysncTask中的应用程序的本地数据库中插入了一些数据,但是当执行该类时,屏幕上没有显示进度对话框,而我可以看到正在运行的日志。我看到很多相关的答案,但问题没有解决。我读了.get()方法阻止了ui,但我已经没有使用这个方法了。我不知道为什么它没有在屏幕上显示
从主Activity调用异步类
AsyncGetDataFromServer task = new AsyncGetDataFromServer(this);
task.execute();
AsyncTask类的代码
public class AsyncGetDataFromServer extends AsyncTask<Void, Void, Boolean> {
ProgressDialog pd;
Context cxt;
DatabaseHandler dbHelper;
private static ArrayList<DataModel> categoryArrayList;
public AsyncGetDataFromServer(Context context) {
// TODO Auto-generated constructor stub
cxt= context;
pd = new ProgressDialog(cxt);
pd.setTitle("Please wait");
pd.setMessage("Loading...");
pd.setCancelable(false);
dbHelper = new DatabaseHandler(cxt);
}
@Override
protected Boolean doInBackground(Void... params)
{
try {
Log.d("do in background","true");
for (int i = 0; i < response.body().getVideoEntity().size(); i++) {
//inserting in categories
VideoEntity videoEntity;
videoEntity = response.body().getVideoEntity().get(i);
dbHelper.insertChannels(videoEntity);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("exception error", e.getMessage());
}
return true;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("on pre execute","true");
pd.show();
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("on post execute","true");
pd.dismiss();
}
}
答案 0 :(得分:0)
将Activity而不是上下文传递给构造函数。例如 -
AsyncGetDataFromServer task = new AsyncGetDataFromServer(MyActivity.this);
task.execute();
答案 1 :(得分:0)
您应该实施方法onProgressUpdate
并使用方法publishProgress
:
请参阅https://developer.android.com/reference/android/os/AsyncTask.html
答案 2 :(得分:0)
在onPreExecute()方法中显示对话框&amp;在onPostExecute()方法中解雇:
private class AsyncGetDataFromServer extends AsyncTask<Void, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(YourClass.this);
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
}
protected void doInBackground(final Void unused) {
//don't interact with the ui!
}
protected void onPostExecute(final Boolean result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}