2013-11-26 56 views
0

我發現我應該在每次使用後關閉我的遊標變量。但問題是當我試圖返回光標作爲函數的輸出。好像這是不可能的。看我DbHelper,我已經試圖接近我的光標和數據庫在我的功能:什麼時候應該關閉遊標變量?

公共類DbHelper擴展SQLiteOpenHelper {

public DbHelper(Context context) { 
    super(context, "shareholders.db", null, 1); 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    try { 
     String sql = "CREATE TABLE IF NOT EXISTS news (id integer,title text,description text,sDate text)"; 
     db.execSQL(sql); 
     sql = "CREATE TABLE IF NOT EXISTS cities (id integer,name text)"; 
     db.execSQL(sql); 
    } catch (Exception e) { 
     xLog.error(e.getMessage()); 
    } 
} 

@Override 
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { 
    // TODO Auto-generated method stub 

} 

public long insert(String table,ContentValues cv){ 
    SQLiteDatabase mydb =this.getWritableDatabase(); 
    long result=-1; 
    try { 
     result = mydb.insert(table,null, cv); 
     }catch (Exception e) { 
     xLog.error(e.getMessage()); 
    } 
    finally{ 
     mydb.close(); 
    } 
    return result; 
} 

public Cursor selectAll(String table){ 
    SQLiteDatabase mydb =this.getReadableDatabase(); 
    String sql = "SELECT * FROM "+table; 
    xLog.info(sql); 
    Cursor result=null; 
    try { 
     result = mydb.rawQuery(sql, null); 
    } catch (Exception e) { 
     xLog.error(e.getMessage()); 
    } 
    finally{ 
     result.close(); 
     mydb.close(); 
    } 
    return result; 
} 

public Cursor select(String table,String where){ 
    SQLiteDatabase mydb =this.getReadableDatabase(); 
    String sql = "SELECT * FROM "+table+" WHERE "+where; 
    xLog.info(sql); 

    Cursor result=null; 
    try { 
     result = mydb.rawQuery("SELECT * FROM "+table+" WHERE "+where, null); 
    } catch (Exception e) { 
     xLog.error(e.getMessage()); 
    } 
    finally{ 
     result.close(); 
     mydb.close(); 
    } 
    return result; 
} 

public long update(String table,ContentValues cv,String condition){ 
    SQLiteDatabase mydb =this.getWritableDatabase(); 
    long result = -1; 
    try { 
     result = mydb.update(table, cv, condition, null); 
    } catch (Exception e) { 
     xLog.error(e.getMessage()); 
    } 
    finally{ 
     mydb.close(); 
    } 
    return result; 
} 

} 

}

如何改變呢?

回答

0

完成使用後,您應該關閉Cursor。如果您將Cursor返回給調用者,那麼您尚未完成。

一些選項:

  • 其接收Cursor變爲負責關閉它的調用者。

  • 您的函數將Cursor中的數據複製到其他數據結構中,關閉遊標並返回複製的數據。

+0

所以,如果我將光標複製到另一個變量,最後我還有一個遊標仍然打開!這有什麼問題嗎? –

+0

請勿複製'Cursor'引用,即將其分配給另一個變量,而是循環遍歷遊標並將每行數據複製到數據結構(如「ArrayList」)。 – laalto

相關問題