2012-03-08 57 views
1

我的代碼如下所示:我應該關閉本地數據庫遊標嗎?

public static synchronized String getPreferenceString(Context context, String key) 
    { 
     Cursor c = DatabaseHelper.getDatabase(context).query(TABLE_NAME, new String[]{ "Value" }, "Key=?", new String[]{ key }, null, null, null, null); 

     if (c.getCount() == 0) 
     { 
      c.close(); 
      return ""; 
     } 

     c.moveToFirst(); 
     String retVal = c.getString(0); 
     c.close(); 

     return retVal; 
    } 

基本上,我得到具體的值了數據庫表。它的偉大工程,但我想我的塗脂抹粉的代碼,以便它也許看起來是這樣的:

public static synchronized String getPreferenceString(Context context, String key) 
    { 
     Cursor c = DatabaseHelper.getDatabase(context).query(TABLE_NAME, new String[]{ "Value" }, "Key=?", new String[]{ key }, null, null, null, null); 

     if (c.getCount() == 0) return ""; 

     c.moveToFirst(); 
     return c.getString(0); 
    } 

是否確定,或者我應該關閉這些遊標?

回答

7
public static synchronized String getPreferenceString(Context context, String key) 
    { 
     Cursor c = DatabaseHelper.getDatabase(context).query(TABLE_NAME, new String[] { "Value" }, "Key=?", 
       new String[] { key }, null, null, null, null); 

     if (c == null) 
      return ""; 

     try {  
      return c.moveToFirst() ? c.getString(0) : ""; 
     } finally { 
      c.close(); 
     } 
    } 

你應該總是關閉光標,除非它是由應用程序以某種方式

+0

要添加,只是因爲它不是」你不應該忽略必要的代碼(與裝載機等的Android AUTOMAGIC東西)管理像漂亮一樣。 – jsimpson 2012-03-08 22:20:45

相關問題