java.lang.IllegalStateException:尝试重新打开一个已经关闭的对象:SQLiteQuery:SELECT * FROM pets

时间:2012-12-07 15:07:59

标签: android sqlite exception cursor

我的申请中有错误。

我是为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();
}

2 个答案:

答案 0 :(得分:3)

我最后通过替换getPetsCount方法解决了这个问题:

public int getPetsCount() {
    String countQuery = "SELECT * FROM " + TABLE_PETS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int count = cursor.getCount();
    cursor.close();
    db.close();
    return count;

答案 1 :(得分:0)

首先,您应该在完成使用后关闭光标(这可能会解决您的问题)

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());
}

// Close cursor when finished using it
cursor.close();

return petList;     
}