Idiom to close a cursor

后端 未结 7 1714
刺人心
刺人心 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:20

    I think @skylarsutton's is a right answer for the question. However, I want to leave codes for the question (any codes in answers seems to have some flaws). Please consider to use my code.

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

提交回复
热议问题