尝试重新打开已经关闭的对象:java.lang.IllegalStateException:?

vin*_*thp 14 android illegalstateexception android-cursor android-activity

我知道这个问题在SO中多次提出过,但我无法弄清楚我的确切问题.

我使用以下代码从数据库(表1)获取数据,并根据检索值更新另一个Table2.它在一些Android版本中工作正常,但是当我用Android 4.0.3进行测试时.我这个迷途java.lang.IllegalStateException:?.attempt to re-open an already-closed objectsum_cursor.moveToNext();.

我在AsyncTask中使用此代码.

 /** Sum of total matched values*/
            Cursor sum_cursor = db.gettotalMatchvalue(this);
             if(sum_cursor!=null)
             {
                 sum_cursor.moveToFirst();
                 for(int j=0; j<sum_cursor.getCount();j++)
                 {    
                     float totalmatchedscore = sum_cursor.getInt(0);
                     float totalingredients = Float.parseFloat(sum_cursor.getString(sum_cursor.getColumnIndex(APPDatabase.CK_TOTALINCREDIENTS)));
                     /**average = totalscore/totalingredients*/
                     double average = totalmatchedscore/totalingredients;
                     int id = Integer.parseInt(sum_cursor.getString(sum_cursor.getColumnIndex(APPDatabase.CK_ID))); 

                 db.updateAverage(id, average); 
                 sum_cursor.moveToNext(); //Here is the problem
                 }  
             }   
             db.close();  
Run Code Online (Sandbox Code Playgroud)

我的更新方法编码

/** Update average */
public void updateAverage(int id,double average)
{
    SQLiteDatabase db = getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(CK_FINALVALUE,average);
    db.update(TABLE, values,CK_ID+" = "+id , null);   
}
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?

我知道很多人遇到过这种情况.你能帮帮我们吗?

谢谢你的帮助.

Gra*_*and 23

迭代查询结果时无法更新表.这有充分的理由; 如果您添加的数据会导致您正在迭代的数据发生变化,该怎么办?您的光标不会返回有效数据.

尝试将数据存储回表中updateAverage()会导致问题.您应该只记住循环期间的平均值,然后在完成光标循环后再更新一次.

为了进一步解释您所获得的确切错误:插入新数据的行为导致数据库关闭当前打开的所有游标,作为安全措施.所以当你sum_cursor.moveToNext()在更新平均值后调用时,光标有点惊讶地发现它已经被关闭了.