【发布时间】:2020-06-13 23:47:54
【问题描述】:
我已经为我所有需要 ProgressDialogs 的后台进程创建了一个 AsyncTask 类,并将它放在我的 Utils java 类中,但是当我尝试调用它时,它在 ProgressDialog 的 show() 方法上出现了描述的错误。
这里是 Utils 类中的 AsyncTask 类:
public static class BackgroundTask extends AsyncTask<Void, Void, Void> {
private WeakReference<Context> context;
private ProgressDialog progressDialog;
private String message;
private Runnable doInBackground;
public BackgroundTask(Context context, String message, Runnable doInBackground) {
this.context = new WeakReference<>(context);
this.message = message;
this.doInBackground = doInBackground;
}
@Override
protected void onPreExecute() {
if (context == null)
return;
progressDialog = new ProgressDialog(context.get(), R.style.dialogStyle);
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setIndeterminate(false);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
doInBackground.run();
return null;
}
@Override
protected void onPostExecute(Void result) {
if(progressDialog != null)
progressDialog.dismiss();
progressDialog = null;
}
}
这就是我在MainActivity 上的称呼:
new Utils.BackgroundTask(this, "Loading...",() -> {
// Something heavy to do
}).execute();
什么问题,我该如何解决。提前致谢。
编辑
在活动中加载片段可能有问题吗?这正是我在我的MainActivity 中所说的:
new Utils.BackgroundTask(this, "Loading...",() -> {
String codeResponse = NetworkConnection.get(this, NetworkConnection.BaseUrl + "sms/code.php?mobile=0" + phoneNumber);
if(codeResponse != null){
this.code = new Gson().fromJson(codeResponse, CheckCodeModel.class).getCode();
Toast.makeText(this, "Code is :" + code + ":", Toast.LENGTH_SHORT).show();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fl_login_fragmentHolder,new LoginCheckCodeFragment(),"CheckCode");
transaction.addToBackStack("CheckCode");
transaction.commit();
}
}).execute();
【问题讨论】:
-
把它放到你的异步任务中 if(progressDialog!=null && progressDialog.isShowing()){progressDialog.dismiss();)
-
@AmanB。我做了,但问题仍然存在。
-
在上下文中,你必须使用“getApplicationContext()”而不是传递“this”。
-
@AmanB。我也尝试过,但
ProgressDialog在这种情况下更快崩溃。Caused by: android.view.InflateException: Binary XML file line #44: Error inflating class com.android.internal.widget.DialogTitle -
检查您的 xml 文件第 44 行。那里有什么?
标签: java android exception android-asynctask progressdialog