1

Here is the code:

public List<XImage> getXImages()
{
    List<XImage> images = new ArrayList<XImage>();

    SQLiteDatabase database = this.getWritableDatabase();

    String sql = String.format("SELECT %s, %s, %s FROM %s",
            A, B, C, TABLE);

    Cursor result = database.rawQuery(sql, null);

    if (result.moveToFirst())
    {
        do
        {
            String a = result.getString(0);
            String b = result.getString(1);
            String c = result.getString(2);

            XImage image = new XImage(a, b, c);
            images.add(image);
        }

        while (result.moveToNext());
    }

    result.close();
    database.close();

    return images;  
}

If after result.close(); I put database.close(); I get a runtime exception saying that it's trying to access SqliteDatabase while the connection is closed.

Does closing the cursor also close the database connection? If not, what should I be doing differently?

Borislav
  • 909
  • 3
  • 10
  • 25
b85411
  • 9,420
  • 15
  • 65
  • 119

2 Answers2

2

I had similar problems before, in the end of every method that works with the database, I had database.close(); and sometimes that throwed exceptions.

Remove database.close(); from around your code, and keep only the cursor close statements, and you should be fine.

Borislav
  • 909
  • 3
  • 10
  • 25
0

I guess you are calling the method from different threads.

However in my opinion, the best practice is never close the database because SQLiteOpenHelper.getWritableDatabase() and SQLiteOpenHelper.getReadablDatabase() always return the same instance if SQLiteOpenHelper.close() hasn't been called. So calling method like yours would mess up the SQLiteDatabase instance's life cycle which rises exceptions.

You might want to check this link out:

http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection

or source code of SQLiteOpenHelper here:

https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/database/sqlite/SQLiteOpenHelper.java

Leo
  • 1,433
  • 23
  • 40