11

我应该使用以下哪两个来确保所有游标都已关闭?

    Cursor c = getCursor(); 

    if(c!=null && c.getCount()>0){ 
        try{ 
            // read values from cursor 
        }catch(..){} 
        finally{ 
            c.close(); 
        } 
    }//end if
    

或者

    Cursor c = getCursor(); 
    try{ 
        if(c!=null && c.getCount()>0){ 
            // read values from cursor 
        }//end if 
    }catch(..){
        
    }finally{ 
        c.close(); 
    } 

请指教。

4

7 回答 7

13

两者都没有,但第二个最接近。

  • 当 getCount() == 0 时选项 1 没有正确关闭光标
  • 选项 2 使 finally 块暴露于空指针异常

我会使用:

Cursor c = getCursor(); 
try { 
    if(c!=null && c.getCount()>0){ 
         // do stuff with the cursor
    }
}
catch(..) {
    //Handle ex
}
finally { 
    if(c != null) {
        c.close(); 
    }
}

...或者如果您希望光标经常为空,您可以将其稍微转动一下:

Cursor c = getCursor(); 
if(c != null) {
    try { 
        if(c.getCount()>0) { 
             // do stuff with the cursor
        }
    }
    catch(..) {
        //Handle ex
    }
    finally { 
        c.close(); 
    }
}
于 2010-11-10T15:48:51.283 回答
3

这甚至更好:

  • 不使用 c.getCount() - 计数可能需要对数据库进行额外的工作并且不需要
  • 在查询块之前初始化游标,所以创建查询失败后不跟finally块

编码:

Cursor c = query(....);
if (c != null) {
   try {        
       while (c.moveToNext()) {  // If empty or after last record it returns false.    
          // process row...
       }
   } 
   finally {
       c.close();
    }
}

请注意,c如果出现错误或空游标,则可能为 null。请参阅https://stackoverflow.com/a/16108435/952135。不过,在空游标的情况下,我会报告 null 返回值作为错误。

于 2013-08-05T07:32:17.937 回答
1

最佳做法如下:

Cursor c = null;    
try {        
   c = query(....);      
   while (c.moveToNext()) {  // If empty or next to last record it returns false.    
      // do stuff..       
   }
} finally {
   if (c != null && !c.isClosed()) {  // If cursor is empty even though should close it.       
   c.close();
   c = null;  // high chances of quick memory release.
}
于 2012-05-03T07:54:56.063 回答
0

取决于您要捕获的内容,但我会说第二个,以防万一c.getCount()引发异常。

此外,一些缩进不会出错:)

于 2010-11-10T12:18:48.807 回答
0

我会说第一个,主要是因为第二个会尝试调用c.close(),即使cis null。此外,根据文档,getCount()不会引发任何异常,因此无需将其包含在try块中。

于 2010-11-10T12:26:16.723 回答
-1

我认为我的答案是最好的:

    Cursor cursor = null;

    try {
        cursor = rsd.rawQuery(querySql, null);
        if (cursor.moveToFirst()) {
            do {
                // select your need data from database
            } while (cursor.moveToNext());
        }
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
            cursor = null;
        }
    }
于 2014-09-13T01:58:53.120 回答
-1

我认为@skylarsutton 是这个问题的正确答案。但是,我想留下问题的代码(答案中的任何代码似乎都有一些缺陷)。请考虑使用我的代码。

Cursor c = query(....);
if (c != null) {
   try {        
       //You have to use moveToFirst(). There is no quarantee that a cursor is located at the beginning.
       for(c.moveToFirst();!c.isAfterLast();c.moveToNext()) {  
          // process row...
       }
   } 
   finally {
       c.close();
    }
}
于 2016-08-29T08:39:54.187 回答