TheLettuceMaster
TheLettuceMaster

Reputation: 15734

Not closing cursor - only pre-Android 4.0?

I am testing an app on Android 4.0+ and it works great. On 2.2/2.3, I keep having issues with SQLlite cursors. The odd part if that this happens like 90% of the time when app starts. I can't explain why it sometimes work.

Here is partial LogCat:

05-01 20:02:30.341: E/Cursor(369): Finalizing a Cursor that has not been deactivated or closed. database = /data/data/com.---.---/databases/cats.db, table = trending_watching, query = SELECT _id, item_id, item, review, review_id, cat, user, url FROM trending_watching
05-01 20:02:30.341: E/Cursor(369): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

Here is where problem happens:

In Splash Screen, I grab values from MySQL and put them in TWO different SQLlite Table. I can verify the table is being populated with data. Splash Screen exits.

The next Activity takes the two SQLLite Tables and gets the data like this:

    // Open Database

watchItemIdList = datasource
        .getWatchStrings(MySQLiteHelper.COLUMN_TREND_WATCH_ITEM_ID);
watchUsers = datasource
        .getWatchStrings(MySQLiteHelper.COLUMN_TREND_WATCH_USER);
watchCats = datasource
        .getWatchStrings(MySQLiteHelper.COLUMN_TREND_WATCH_CAT);
watchReviews = datasource
        .getWatchStrings(MySQLiteHelper.COLUMN_TREND_WATCH_REVIEW);
watchReviewId = datasource
        .getWatchStrings(MySQLiteHelper.COLUMN_TREND_WATCH_REVIEW_ID);
watchItems = datasource
        .getWatchStrings(MySQLiteHelper.COLUMN_TREND_WATCH_ITEM);
watchUrl = datasource
        .getWatchStrings(MySQLiteHelper.COLUMN_TREND_WATCH_URL);

     // Close database

It gets the data here:

public List<String> getWatchStrings(String dbColumn) {

    Cursor cursor = database.query(MySQLiteHelper.TABLE_WATCHING_REVIEWS,
            allTrendWatchingColumns, null, null, null, null, null);

    List<String> array = new ArrayList<String>();
    while (cursor.moveToNext()) {
        String uname = cursor.getString(cursor.getColumnIndex(dbColumn));
        array.add(uname);
    }
    return array;

}

The app keeps crashing, I believe from that LogCat on this line:

Cursor cursor = database.query(MySQLiteHelper.TABLE_WATCHING_REVIEWS,
            allTrendWatchingColumns, null, null, null, null, null);

Upvotes: 0

Views: 168

Answers (2)

Gustek
Gustek

Reputation: 3760

cursor.close();

just before You return, cursors have to be closed manually.

Upvotes: 1

j2emanue
j2emanue

Reputation: 62549

call this after your cursor is defined:

startManagingCursor(Cursor);

this tells the activity to begin managing the cursor's life based on the activity's lifecycle

Upvotes: 0

Related Questions