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

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 {
    ...
    }

}


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

    @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欺骗我还是我误解了?

最佳答案

ProgressDialogContext中获得Constructor,但是您在onPreExecute中使用了this。相反,您应该写YourActivity.this(活动的各自名称)

注意:

导致此错误的原因可能是试图通过不是dialogContext显示应用程序Activity



试试这个

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 {
...
}

}

10-07 19:14