android - 关闭游标的成语

标签 android sqlite android-cursor

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

    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(); 
    } 

请指教。

最佳答案

两者都不是,但第二个最接近。

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

我会使用:

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

...或者如果您希望游标经常为 null,您可以将其稍微翻转一下:

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

关于android - 关闭游标的成语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4144328/

相关文章:

android - 谷歌机器学习套件 : Waiting for the text recognition model to be downloaded

android - "Appdriver"类似于 Android 应用的 Webdriver

java - 如何在不访问上下文的情况下从线程更新我的 Android SQLite 数据库?

android - 在android中使用CursorLoader代替startManagingCursor,数据库访问

Android 媒体播放器服务最佳实践

android:imeOptions ="actionNext"在不指定 android:inputType 的情况下不起作用

sql - 将查询分组为组和子组

python - 如何在Python中打印出电话号码?

Android - 从特定 Thread_ID 查询所有彩信和短信