Unable to return Cursor object - close() was never

2019-05-19 03:23发布

问题:

Hey. I'm trying to return a cursor object to my activity where its gonna be used in a SimpleCursorAdapter, but Im having a close() was never explicity called error. I cant find any solution for this error, and I'm about to think that its a non-solution error, LOL.

Think with me.

The error says:

close() was never explicitly called on database '/data/data/com.example.myapp/databases/myDB.db'

And has a warning too:

Releasing statement in a finalizer. Please ensure that you explicitly call close() on your cursor: SELECT * FROM contact_data ORDER BY duration desc

android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

The error is in this method, that is in the class DataHandlerDB (deals with database)

public static Cursor selectTopCalls(Context ctx) {

        OpenHelper helper = new OpenHelper(ctx);
        SQLiteDatabase db = helper.getWritableDatabase(); // error is here

        Cursor cursor = db.query(TABLE_NAME_2, null, null, null, null, null,
                "duration desc");

        return cursor;
    }

This method is used on my activity, by this following method:

public void setBasicContent() {

    listview = (ListView) findViewById(R.id.list_view); 

    Log.i(LOG_TAG, "listview " + listview);

    Cursor c = DataHandlerDB.selectTopCalls(this); // here I use the method
    startManagingCursor(c);

    adapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {               
            DataHandlerDB.CONTACT_NAME_COL,
            DataHandlerDB.CONTACT_NUMBER_COL,
            DataHandlerDB.CONTACT_DURATION_COL,
            DataHandlerDB.CONTACT_DATE_COL }, new int[] {
            R.id.contact_name, R.id.phone_number, R.id.duration, R.id.date });

    Log.i(LOG_TAG, "before setAdapter");

    Toast.makeText(this, "Before setAdapter", Toast.LENGTH_SHORT).show();

    listview.setAdapter(adapter);


}

I try to close the cursor and database inside this method, but when I do that, the error is not fixed, and it doesnt print my list.

I tried to close it on the selectValues() method, but when doing that, it says, trying to re-open cursor already closed (something like that).

I also tried to close the cursor and database in onDestroy(), onStop() but it didnt worked.

Thats why I thought there were no soluytion for that. What am I supose to do?

The class DataHandlerDB.java, has a createDB() method:

public static SQLiteDatabase createDB(Context ctx) {
        OpenHelper helper = new OpenHelper(ctx);
        SQLiteDatabase db = helper.getWritableDatabase();
        helper.onOpen(db);
        db.close();
        return db;
    }

And an Inner Class called OpenHelper(extends SQLiteOpenHelper)

public static class OpenHelper extends SQLiteOpenHelper {

        private final Context mContext;

        OpenHelper(Context context) {

            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.mContext = context;

        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            String[] sql = mContext.getString(
                    R.string.MyString_OnCreate).split("\n");

            db.beginTransaction();

            try {
                execMultipleSQL(db, sql);
                db.setTransactionSuccessful();
            } catch (SQLException e) {

                Log.e("Error creating tables and debug data", e.toString());
                throw e;

            } finally {
                db.endTransaction();

            }
        }

        private void execMultipleSQL(SQLiteDatabase db, String[] sql) {

            for (String s : sql) {

                if (s.trim().length() > 0) {

                    db.execSQL(s);
                }
            }

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            /*
             * Log.w("My Database",
             * "Upgrading database, this will drop tables and recreate.");
             * db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db);
             */
        }

        @Override
        public void onOpen(SQLiteDatabase db) {

            super.onOpen(db);
        }

    }

So anyone can help me to fix this problem?? Thanks!

回答1:

Instead of creating a new OpenHelper in each of your static methods, instantialize your DataHandlerDB with the current context and have the class hold a variable populated by getWritableDatabase. You are creating multiple cursor objects created by different SQLiteOpenHelper objects and Android doesn't like doing this.

Check this out for additional info: http://www.ragtag.info/2011/feb/1/database-pitfalls/

Here's how it looks to me like you're doing things...

public class DataHandlerDB{

    public static SQLiteDatabase createDB(Context ctx) {
        OpenHelper helper = new OpenHelper(ctx);
        SQLiteDatabase db = helper.getWritableDatabase();
        ...
        return db;
    }

    public static Cursor selectTopCalls(Context ctx) {
        OpenHelper helper = new OpenHelper(ctx);
        SQLiteDatabase db = helper.getWritableDatabase(); // error is here
        ...
        return c;
    }

}

This results in multiple concurrent SQLiteOpenHelper objects and multiple SQLiteDatabase objects and the locking situation you currently have.

Instead of doing multiple Static calls, make a DataHandler class that you instantialize with the consistent context and then make normal calls (instead of static ones):

public class DataHandlerDB{
    OpenHelper _helper;
    SQLiteDatabse _db;

    public DataHandlerDB( Context ctx ){
        _helper = new OpenHelper(ctx);
        _db = _helper.getWritableDatabase();
    }

    public SQLiteDatabase createDB() {
        ...
        return db;
    }

    public Cursor selectTopCalls() {
        ...
        return c;
    }

}

public void setBasicContent() {

    ...

    DataHandlerDB handler = new DataHandlerDB( this );
    Cursor c = handler.selectValues();  //.selectTopCalls()?

    ...
}

When you create this object, it will persist 1 OpenHelper and 1 SQLiteDatabase. This should alleviate the problems with SQLite wanting the database closed before it can access it.

Don't forget to close the DB in the onDestroy method of your activity.