我创建了一些CursorWrapper类
public class DogsCursorWrapper extends CursorWrapper {
public DogsCursorWrapper(Cursor cursor) {
super(cursor);
}
public Dog getDog() {
Dog dog = new Dog();
dog.setDogId(getInt(getColumnIndex(DogTable.ID)));
dog.setDogName(getString(getColumnIndex(DogTable.NAME)));
dog.setDogKind(getString(getColumnIndex(DogTable.KIND)));
return dog;
}
}
然后我使用queryDogs方法填充游标,然后返回包装类的实例
private DogsCursorWrapper queryDogs() {
Cursor simpleCursor = db.query(
DogTable.TABLE_NAME, null,null,null,null,null,null);
DogsCursorWrapper dogsCursor = new DogsCursorWrapper(simpleCursor);
// simpleCursor.close(); // this line causes an error in runtime
return dogsCursor;
}
下一步,我在以下方法中调用上述方法:
private void loadDogs() {
DogsCursorWrapper dogsCursor;
dogs = new ArrayList<>();
try {
dogsCursor = queryDogs();
dogsCursor.moveToFirst();
while (!dogsCursor.isAfterLast()) {
dogs.add(dogsCursor.getDog());
dogsCursor.moveToNext();
}
} finally {
dogsCursor.close();
}
}
实际上,我确实在最后一种方法中关闭了dogsCursor
,我的问题是:我是否没有错过必须关闭的光标?需要明确的是,我对simpleCursor
方法中的queryDogs
有一些疑问。我应该关闭那个吗?
以这种方式使用自定义DogsCursorWrapper类是否正确?非常感谢!
答案 0 :(得分:1)
已被注释掉的行:
// simpleCursor.close(); // this line causes an error in runtime
是不必要的。我想您是在问:它会复制光标吗?答案是不。游标包装使用传入的游标。
最简单的验证方法是:
private DogsCursorWrapper queryDogs() {
Cursor simpleCursor = db.query(
DogTable.TABLE_NAME, null,null,null,null,null,null);
DogsCursorWrapper dogsCursor = new DogsCursorWrapper(simpleCursor);
simpleCursor.close(); // this line causes an error in runtime
if (dogsCursor.isClosed()) { // Because of this
Log.w(TAG, "Houston we have a problem...");
}
return dogsCursor;
}
运行此代码说明,关闭原始光标也会关闭CursorWrapper所保存的光标。