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

RuntimeException: Can't create handler in onPreExecute()

我收到 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 class 中从 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 的各自名称)

注:

此错误的原因可能是试图通过 Context 而非 Activity

显示应用程序 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 {
...
}

}