ogarcia / opensudoku

Open Source Sudoku game for Android.
GNU General Public License v3.0
328 stars 144 forks source link

Database resource leaks #129

Closed nikclayton closed 2 years ago

nikclayton commented 3 years ago

The current code logs warnings about resource leaks, in particular database leaks.

E.g., in

    public FolderInfo getFolderInfo(long folderID) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        qb.setTables(FOLDER_TABLE_NAME);
        qb.appendWhere(FolderColumns._ID + "=" + folderID);

        SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // XXX
        try (Cursor c = qb.query(db, null, null, null, null, null, null)) { // XXX
            if (c.moveToFirst()) {
                long id = c.getLong(c.getColumnIndex(FolderColumns._ID));
                String name = c.getString(c.getColumnIndex(FolderColumns.NAME));

                FolderInfo folderInfo = new FolderInfo();
                folderInfo.id = id;
                folderInfo.name = name;

                return folderInfo;
            } else {
                return null;
            }
        }
    }

the db handle is leaked because db.close() is not called.

The two lines marked XXX can be replaced with:

        try (SQLiteDatabase db = mOpenHelper.getReadableDatabase(); Cursor c = qb.query(db, null, null, null, null, null, null)) {

which will use try-with-resources and close db when it goes out of scope too. That solves some of the problems, but I've noticed that getFolderList leaks as well:

    public Cursor getFolderList() {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        qb.setTables(FOLDER_TABLE_NAME);

        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        return qb.query(db, null, null, null, null, null, "created ASC");
    }

I suspect the "correct" fix is write the database handling in terms of https://developer.android.com/reference/androidx/lifecycle/ViewModel and https://developer.android.com/reference/androidx/lifecycle/LiveData, which I think are supposed to resolve issues like this.

ogarcia commented 2 years ago

I'm migrating Open Sudoku development from GitHub to GitLab. To make the migration as clean as possible I'm going to close this issue. If you are still interested (or if it is still relevant), please open it again in GitLab from July 26.

Thank you very much for your understanding.