我得到一个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
欺骗我还是我误解了? 最佳答案
ProgressDialog
在Context
中获得Constructor
,但是您在onPreExecute中使用了this
。相反,您应该写YourActivity.this
(活动的各自名称)
注意:
导致此错误的原因可能是试图通过不是dialog
的Context
显示应用程序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 {
...
}
}