【问题标题】:RuntimeException: Can't create handler in onPreExecute()RuntimeException:无法在 onPreExecute() 中创建处理程序
【发布时间】:2015-03-12 08:22:19
【问题描述】:

我收到了java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(),而且,我知道,这意味着我正在尝试在不是 UI 线程的线程中进行一些 UI 修改。让我担心的是,我在 onPreExecute()AsyncTask 中遇到了异常,这就是 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 是在欺骗我还是我误会了什么?

【问题讨论】:

  • 你在这个调用构造函数中传递了什么CreateDatabaseTask?以及从哪里执行 AsyncTask ?
  • 你能发布你的完整的errace跟踪吗

标签: android multithreading android-asynctask runtimeexception


【解决方案1】:

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

注意:

此错误的原因可能是尝试通过不是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 {
...
}

}

【讨论】:

  • 这个类在它自己的文件中,所以我有一个No enclosing instance of the type MyActivity is accessible in scope。无论如何,我解决了将dialog = new ProgressDialog... 移动到构造函数中的问题,但我想知道我做错了什么:)
  • 此错误的原因可能是试图通过不是 ActivityContext 显示应用程序 dialog
  • 你是对的,上下文不是一个活动 :) 我建议你编辑你的答案,以便我接受它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多