Reputation: 10695
android.database.sqlite.SQLiteOpenHelper
provides the ability to use an in-memory database if the name argument to its constructor is null
:
String: of the database file, or null for an in-memory database
If SQLiteOpenHelper
is instantiated multiple times with a null
name argument, do they access the same in-memory database or is a separate in-memory database created each time?
Upvotes: 7
Views: 1884
Reputation: 192043
If we look at the source code, we see that in the constructor mName
would get set to null
.
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version,
DatabaseErrorHandler errorHandler) {
if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version);
mContext = context;
mName = name;
mFactory = factory;
mNewVersion = version;
mErrorHandler = errorHandler;
}
Which means getDatabaseName()
returns null
.
public String getDatabaseName() {
return mName;
}
Later, through the use of getReadableDatabase()
or getWritableDatabase()
, if mName
is null
, then it calls the create
method for an in-memory database instead of trying to opening one from disk.
if (mName == null) {
db = SQLiteDatabase.create(null); // in-memory
} else {
// db file opened or created
}
...
return db;
That db
variable is maintained in the SQLiteOpenHelper
until it is closed, which in the case of an in-memory database, means the data is deleted.
To clarify,
Each instance of a SQLiteOpenHelper
that uses an in-memory database will its own database while the same instance will use one database and persist that data until it is closed.
Upvotes: 3
Reputation: 5741
From SQLite official documentation In-Memory Databases
Opening two database connections each with the filename ":memory:" will create two independent in-memory databases.
In Android, pass null instead of ":memory:"
So, If you instantiate SQLiteOpenHelper multiple times with a null name argument then it create separate in-memory database created each time
Upvotes: 8