【发布时间】:2012-12-07 15:07:58
【问题描述】:
我的申请有错误。
我是为 android 制作应用程序的新手,所以我现在不知道出了什么问题...
这是在日志中:
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM pets
我有一个 SQLite 数据库,其中有这种方法:
public List<Pet> getAllPets() {
List<Pet> petList = new ArrayList<Pet>();
String selectQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Pet pet = new Pet();
pet.setID(Integer.parseInt(cursor.getString(0)));
pet.setName(cursor.getString(1));
pet.setAge(cursor.getString(2));
petList.add(pet);
} while (cursor.moveToNext());
}
return petList;
}
然后我在其他活动中使用数据库中的这个方法来用每只宠物的名字填充 ListView....
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
PetListView = (ListView)findViewById(R.id.list);
MyDatabaseHelper db = new MyDatabaseHelper(this);
String [] items = new String[db.getPetsCount()];
List<Pet> pets = db.getAllPets();
for (int i = 0; i < db.getPetsCount(); i++) {
items[i] = pets.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, items);
PetListView.setAdapter(adapter);
}
当这个活动启动时,应用程序崩溃了..
拜托,你能告诉我穿了什么吗?我该如何解决?非常感谢您的帮助。
编辑:
getPetsCount() 方法:
public int getPetsCount() {
String countQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
【问题讨论】:
-
你能发布 getPetsCount() 方法吗?
-
关闭游标并关闭数据库 ex:db.close()。您可能也在其他地方的某个地方调用了 db 创建方法。那是你得到了例外,我觉得。
-
@kumar 我应该在哪里关闭数据库和光标?当提琴手回答我的问题时,我试图关闭光标,但没有帮助。它仍然抛出相同的异常......
-
if db.getPetsCount();此方法具有 db 关闭语句。那么您必须在执行 db.getAllPets() 之前再次获取数据库连接。所以最好在 getPetsCount() 中关闭数据库。并在调用 getAllPets() 方法之前再次打开数据库连接。
标签: android sqlite exception cursor