2012-12-07 43 views
0

我的應用程序出現錯誤。java.lang.IllegalStateException:嘗試重新打開已關閉的對象:SQLiteQuery:SELECT * FROM pets

我在做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(); 
} 
+0

你可以發佈getPetsCount()方法嗎? – fiddler

+0

關閉遊標並關閉數據庫ex:db.close()。您可能也在其他地方的某處調用了數據庫創建方法。那是你感覺到的例外。 – kumar

+0

@kumar在哪裏我應該關閉數據庫和光標?我試圖關閉遊標,因爲提琴手在我的問題上回答,但它沒有幫助。它仍會拋出異常.... – andrew

回答

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; 
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;  
} 
相關問題