Idiom to close a cursor

后端 未结 7 1701
刺人心
刺人心 2021-02-08 03:57

Which of the following two should I be using to make sure that all the cursors are closed?

    Cursor c = getCursor(); 

    if(c!=null && c.getCount()&g         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-08 04:17

    Best practice is the one below:

    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.
    }
    

提交回复
热议问题