Idiom to close a cursor

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

    This is even better:

    • does not use c.getCount() - counting might require extra work for the database and is not needed
    • initialize the cursor before the query block, so failure to create the query is not followed by the finally block

    The code:

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

    Note that c might be null in case of error or empty cursor. See https://stackoverflow.com/a/16108435/952135. I would report null return value in case of empty cursor as a bug, though.

提交回复
热议问题