关闭Cursor上的IllegalStateException

时间:2010-06-18 16:52:07

标签: android cursor

我的问题似乎与以下问题有关:

How to Handle in code IllegalStateException on Cursor?

违规方法的代码如下:

    public boolean isPermanent(String screen_name) {
    boolean output = false;
    try {
        Cursor c = mDb.query(USERS, new String[] {PERMANENT}, NAME + "='" + screen_name + "'", null, null, null, null);
        if (c != null && c.getCount() > 0) {
            c.moveToFirst();
            output = c.getString(0).contentEquals("C");
            c.close();
        }
    }
    catch (Exception e) {
        Log.e("DBERR", e.getMessage());
    }
    return output;
}

但是,当抛出异常时,我正在查看有问题的Cursor,我可以在Eclipse中看到以下内容:

this    SQLiteCursor  (id=830061188288) 
mClosed true    
mColumnNameMap  null    
mColumns    String[1]  (id=830061188608)    
mContentObservable  ContentObservable  (id=830061188456)    
mContentResolver    null    
mCount  0   
mCurrentRowID   null    
mCursorState    0   
mDatabase   SQLiteDatabase  (id=830060407768)   
mDataSetObservable  DataSetObservable  (id=830061188408)    
mDriver SQLiteDirectCursorDriver  (id=830061143904) 
mEditTable  "users" (id=830060403008)   
mInitialRead    2147483647  
mLock   null    
mMaxRead    2147483647  
mNotificationHandler    null    
mNotifyUri  null    
mPendingData    false   
mPos    -1  
mQuery  SQLiteQuery  (id=830061143936)  
mRowIdColumnIndex   -1  
mSelfObserver   null    
mSelfObserverLock   Object  (id=830061188504)   
mSelfObserverRegistered false   
mStackTraceElements null    
mUpdatedRows    HashMap  (id=830061144056)  
mWindow null    

这清楚地表明Cursor的状态是关闭的,因为它应该是 - 所以任何人都有任何关于为什么这应该抛出异常的线索?

1 个答案:

答案 0 :(得分:1)

而不是检查c.getCount()> 0,检查c.moveToNext():

try{
...
    if (c != null && c.moveToNext())
    //do your thing here and don't call moveToFirst()
} finally {
    if (c != null)
    c.close();
}

然后移动到最后{}