2010-06-18 55 views
1

我的问题似乎与下面的问题:IllegalStateException异常闭馆光标

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

不过,我在看在抛出异常时光标出现,我可以在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  

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

+0

哪条线恰好引发错误?我也将c.close()移到finally子句中。 – 2010-06-18 17:04:35

+0

从系统守护进程线程抛出异常,我会尝试移动到最后,但看看是否有帮助 – frak 2010-06-18 17:11:01

+0

在没有元素的情况下游标成功返回的情况下也存在内存泄漏 - 游标永远不会获取在这种情况下关闭。我强烈建议一次检查一项 - 检查c是否为空,如果是,则返回错误。那么如果它不为空,c.getcount()。如果计数为零,则关闭光标等。务必记住关闭光标。 – 2010-06-18 17:31:58

回答

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

并移动接近最后{}

+0

到目前为止,这似乎已经做了伎俩,只有时间会告诉,因为它似乎随机发生,但谢谢你 – frak 2010-06-18 17:44:39

+0

如果查询只返回一行,moveToNext()将返回false。 – cdonner 2010-06-30 03:28:11

相关问题