重新开放已经关闭

时间:2012-12-02 20:47:20

标签: android sqlite

当我在:

中使用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(),则不会发生错误。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

attempt to re-open an already-closed object:

异常告诉你很多!

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

答案 1 :(得分: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;
    }