我应该使用以下哪两个来确保所有游标都已关闭?
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/