What is the proper way to keep a reference to your SQLiteDatabase
through out the lifespan of your application?
Currently, I have a class that looks something like this:
public class myApp {
public static SQLiteDatabase DB;
//...
}
Then in my class that extends Application
, onCreate()
I check if myApp.DB
is null
and if it is, create a new SQLiteOpenHelper
class and set it to getWritableDatabase()
. Through out my app, I reference myApp.DB
for various queries and such.
This works fine under local testing purposes, but others are experiencing instances where this creates strange behavior (Mostly when trying to determine a table's existence by using select DISTINCT tbl_name from sqlite_master where tbl_name = 'myTable'
) -- at a guess, I'm thinking that something is happening to cause the myApp.DB
reference to be GCed. This makes me believe I need to do that same check for null before interacting with the database, but I don't like the idea of making that check before every single DB interaction (possibly by wrapping all queries in my own method that calls that check first).
So what is the best practice to maintain a reliable reference to your database? Should I instead be keeping a reference to the SQLiteOpenHelper
and do getWriteableDatabase
before every interaction?