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

时间:2015-03-12 08:22:20

标签: android multithreading android-asynctask runtimeexception

我得到java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(),而且,因为我知道,这意味着我试图在不是UI线程的线程中进行一些UI修改。令我担心的是,我在onPreExecute()的{​​{1}}内获得了异常,这是UI线程:

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(); } 是在欺骗我还是我想念一些东西?

1 个答案:

答案 0 :(得分:1)

ProgressDialog获取Context中的Constructor,但您在onPreExecute中使用了this。相反,您应该写YourActivity.this您的活动的相应名称

注意:

此错误的原因可能是尝试通过不是dialog的{​​{1}}显示应用Context


试试这种方式

Activity