【发布时间】:2012-01-02 05:58:48
【问题描述】:
我有一个将 SimpleCursorAdapter 作为字段的类。该适配器用于提供具有 viewBinder 的列表视图。
我有一个运行的异步任务,它向数据库添加一个条目,然后更新游标。
在测试中,如果我在运行异步进程的按钮上单击的太快,我会收到错误:
java.lang.RuntimeException: An error occured while executing doInBackground()
...
Caused by: java.lang.IllegalStateException: database [path_to_my_db] already closed
代码完美运行 - 除非...用户连续快速单击保存按钮...我对这一切都很陌生,因此非常感谢任何输入!
这是我正在尝试做的精简版:
public class MyActivity extends Activity {
private DatabaseConnector connector; // this is my class for managing SQLite
private SimpleCursorAdapter adapter;
....
@Override
public void onCreate(Bundle savedInstanceState){
...
myListView = (ListView)findViewById(R.id.my_list_view);
String[] = new String{"This", "part", "is", "working"};
int[] to = new int[] {1,2,3,4}; // again, this is working...
adapter = new SimpleCursorAdapter(this, R.layout.my_list_item_row, null, from, to);
adapter.setViewBinder(new ViewBinder(){
... // this is all working
... // the viewBinder is for custom date formatting... again, all works
});
myListView.setAdapter(adapter);
}
private class MyAsyncTask extends AsyncTask<Context, Void, ExerciseInstanceViewModel>{
MyViewModel vm; // this viewModel has a cursor member...
public MyAsyncTask([variables-all-working]){
}
@Override
protected MyViewModel doInBackground(Context... params) {
connector = new DatabaseConnector(MyActivity.this);
connector.open(); // TODO: Getting 'did not close database error here...'
vm = connector.runMethodThatIncludesCursorInReturnType([input-paramters-working]);
return vm;
}
// use the cursor returned from the doInBackground method
@Override
protected void onPostExecute(MyViewModel result){
super.onPostExecute(result);
// set instance fields in outer class...;
// set textView, progressBar, etc..
if (result.MyCursor != null)
{
adapter.changeCursor(result.MyCursor);
}
connector.close(); // aren't i closing the db here???
[Code to reload page with next detail items]
}
}
}
【问题讨论】:
-
为什么不简单地在 onPreExecute() 中使 Save 按钮不可点击,并在 onPostExecute() 中再次使其可点击
-
嗨 midoalageb - 好问题,我在原始帖子中显然不够清楚。该按钮的标题为“保存并下一步”。保存数据后,视图会重新加载列表中的下一条记录。这就像逐步浏览客户及其订单的列表。当页面重新加载时,保存&next按钮是可点击的。
-
尝试使用Synchronized语句防止多个线程同时访问同一个变量
标签: android sqlite android-asynctask simplecursoradapter