1

当我在中使用getPesoCount()类似时:

Log.v("SQL", String.valueOf(getPesoCount()));

我收到一个错误:

致命异常:主要
java.lang.IllegalStateException:尝试重新打开已经关闭的对象:android.database.sqlite.SQLiteQuery(mSql = SELECT * FROM pesoTable)...

 public void addPeso(int peso, String date) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_PESO, peso); // Contact Name
        values.put(KEY_DATE, date); // Contact Phone Number

        // Inserting Row
        db.insert(TABLE_PESO, null, values);
        Log.v("SQL", String.valueOf(getPesoCount()));
        db.close(); // Closing database connection

    }


    public int getPesoCount() {
        String countQuery = "SELECT  * FROM " + TABLE_PESO;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

如果我不使用 getPesoCount(),则不会发生错误。

有人能帮我吗?

4

2 回答 2

2
attempt to re-open an already-closed object:

异常告诉你很多!

如果您想cursor进一步使用,请不要cursor.close();在确定不再需要它时调用它。

于 2012-12-02T20:57:14.240 回答
0
 public void addPeso(int peso, String date) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_PESO, peso); // Contact Name
        values.put(KEY_DATE, date); // Contact Phone Number

        // Inserting Row
        db.insert(TABLE_PESO, null, values);
        Log.v("SQL", String.valueOf(getPesoCount(db)));
        db.close(); // Closing database connection

    }




    public int getPesoCount(db) {
        String countQuery = "SELECT  * FROM " + TABLE_PESO;
        Cursor cursor = db.rawQuery(countQuery, null);
        int count = cursor.getCount();
        cursor.close();
        return count;
    }
于 2012-12-02T20:58:30.093 回答