SQLiteDatabase close() function causing NullPointerException when multiple threads

后端 未结 4 1333
小鲜肉
小鲜肉 2020-11-30 13:00

I discovered in my project that the close() function in the SQLiteDatabase implementation on Android throws a NullPointerException when running multiple threads that open th

相关标签:
4条回答
  • 2020-11-30 13:31

    You don't need to bother. See this discussion which includes confirmation that closing the database is done by the system as needed if/when the process is killed off.

    The relevant quote, from a Google employee, is:

    A content provider is created when its hosting process is created, and remains around for as long as the process does, so there is no need to close the database -- it will get closed as part of the kernel cleaning up the process's resources when the process is killed.

    0 讨论(0)
  • Looks similar to this issue: SQLiteDatabase close() function causing NullPointerException when multiple threads

    You may not need to call database.close()

    0 讨论(0)
  • 2020-11-30 13:47

    If you are working directly on a SQLite database without resorting to a content provider, a pattern I have seen used is to close the database in Application.onTerminate, whereas the Application instance stores the singleton database "adapter", which would be an object containing a SQLiteDatabase and its SQLiteOpenHelper.

    0 讨论(0)
  • 2020-11-30 13:50

    I have your answers!

    Never close the db. It is that simple.

    Make sure you only have one, repeat, *one Helper instance per application. Share it with all threads.

    http://www.touchlab.co/blog/single-sqlite-connection/

    Here's some more info on the internals of sqlite and locking:

    http://www.touchlab.co/blog/android-sqlite-locking/

    0 讨论(0)
提交回复
热议问题