3

I'm looking through the NotePad example that comes with the Android SDK and I was wondering if someone could clarify why the the variable db is never closed in the update function? It's usually a good idea to close the database when it is no longer in use to prevent leaks. Ideas?

    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {

        // Opens the database object in "write" mode.
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();

        ... // More code, db.close() is never called?!

        // Returns the number of rows updated.
        return count;
    }
William Seemann
  • 3,440
  • 10
  • 44
  • 78
  • It may sound strangely, but... in Android you should always have only one instance of `SQLiteOpenHelper` and you should never close it. Otherwise, you will get into problems in a multithreaded environment – Vladimir Mironov Jan 10 '13 at 21:28
  • @philipp provided a good answer in this thread: http://stackoverflow.com/questions/4547461/closing-the-database-in-a-contentprovider – DustinB Jan 10 '13 at 22:22
  • I saw that thread. Although the answer is somewhat helpful It doesn't clearly define what a "process" is. If a Service could be classified as a process that implies all database connections created inside a service would remain open until the service is killed. That would potentially cause a leak. – William Seemann Jan 10 '13 at 23:01
  • There should be only *one* connection - and in most cases it would be kept open for the lifetime of the service. – RocketRandom Nov 13 '15 at 08:17

0 Answers0