我的申请中有错误。
我是为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();
}