gpt4 book ai didi

android - RuntimeException:无法在 onPreExecute() 中创建处理程序

转载 作者:行者123 更新时间:2023-11-30 02:17:52 25 4
gpt4 key购买 nike

我得到一个 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(),据我所知,这意味着我尝试在非 UI 线程的线程中进行一些 UI 修改。让我担心的是,我在 AsyncTaskonPreExecute() 中遇到异常,这是 UI 线程:

public class CreateDatabaseTask extends AsyncTask<String, Void, Boolean> {

private static final String TAG = "CreateDatabaseTask";

private SQLiteHelper helper;
private ProgressDialog dialog;

private Context context;

public CreateDatabaseTask(Context context) {
this.context = context;
}

@Override
protected void onPreExecute() {

helper = new SQLiteHelper(context);
dialog = new ProgressDialog(context); // <--- Just here!

if (!helper.checkExists()) {
dialog.setMessage("Iniciando por primera vez...");
dialog.show();
}
}

@Override
protected Boolean doInBackground(String... params) throws SQLException {
...
}

}

我在自定义 SQLiteOpenHelper 类中从 public void onUpgrade(...) 调用 CreateDatabaseTask 构造函数:

    @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

try {
deleteDatabase();
} catch (IOException e) {
e.printStackTrace();
}

CreateDatabaseTask task = new CreateDatabaseTask(context); //<--- I'm calling the constructor here
task.execute();
}

那么,这个 AsyncTask 是在欺骗我还是我误解了什么?

最佳答案

ProgressDialogConstructor 中获取 Context 但您在 onPreExecute 中使用了 this。相反,您应该编写 YourActivity.this(您的 Activity 的相应名称)

备注:

此错误的原因可能是试图通过不是 ActivityContext 显示应用程序 dialog


试试这个方法

public class CreateDatabaseTask extends AsyncTask<String, Void, Boolean> {

private static final String TAG = "CreateDatabaseTask";

private SQLiteHelper helper;
private ProgressDialog dialog;

private Context context;

public CreateDatabaseTask(Context context) {
this.context = context;
dialog = new ProgressDialog(YourActivity.this); //context should be instance of the Activity
}

@Override
protected void onPreExecute() {

helper = new SQLiteHelper(context);


if (!helper.checkExists()) {
dialog.setMessage("Iniciando por primera vez...");
dialog.show();
}
}

@Override
protected Boolean doInBackground(String... params) throws SQLException {
...
}

}

关于android - RuntimeException:无法在 onPreExecute() 中创建处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29004890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com