2012-10-24 315 views
2

Possible Duplicate:
Android error - close() was never explicitly called on database如何避免

「關閉()從未被明確SQLiteDatabase呼籲數據庫」我已經在我的Android應用程序有問題。

我有一個單獨實現其與下面的代碼的方法:

public Cursor getFooCursor(Context context) 
{ 
    StorageDBOpenHelper helper = new StorageDBOpenHelper(context); 
    SQLiteDatabase db = helper.getReadableDatabase(); 

    Cursor c = db.query("Foo", new String[] {"_id", "Titel"}, null, null, null, null, "Test DESC"); 

    return c; 
} 

,當我用這個,我有時會收到錯誤:SQLiteDatabase: close() was never explicitly called on database

如何避免這種情況?問題是,我不能簡單地做一個db.close() befor我return c,因爲然後它的空。

回答

2

我用的就是這種方法對db的實例傳遞到類返回cursor

StorageDBOpenHelper helper = new StorageDBOpenHelper(context); 
SQLiteDatabase db = helper.getReadableDatabase(); 

public Cursor getFooCursor(Context context, SQLiteDatabase db) { 
     Cursor c = db.query("Foo", new String[] {"_id", "Titel"}, null, null, null, 
null, "Test DESC"); 
     return c; 
} 

db.close(); 
2

客戶端應打開數據庫,然後使用此方法獲取遊標,然後在遊標完成時關閉遊標和數據庫。我會建議不要在這裏使用單身人士。相反,做這樣的事情:

public class FooDB 
{ 
    private SQLiteDatabase db = null; 

    private void open() throws SQLiteException 
    { 
     if (db != null) 
     { 
      throw new SQLiteException("Database already opened"); 
     } 

     // Create our open helper 
     StorageDBOpenHelper helper = new StorageDBOpenHelper(context); 
     try 
     { 
      // Try to actually get the database objects 
      db = m_openHelper.getWritableDatabase(); 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 

     if (db == null) 
     { 
      throw new SQLiteException("Failed to open database"); 
     } 
    } 

    private void close() throws SQLiteException 
    { 
     if (db != null) 
     { 
      db.close(); 
      db = null; 
     }   
    } 

    public Cursor getFooCursor(Context context) 
    { 
     if(db == null) 
      throw new SQLiteException("Database not open");  

     Cursor c = db.query("Foo", new String[] {"_id", "Titel"}, null, null, null, null, "Test DESC"); 

     return c; 
    } 
}