SQLiteOpenHelper

public abstract class SQLiteOpenHelper
extends Object implements AutoCloseable



A helper form to manage database cosmos and version management.

Y'all create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes intendance of opening the database if it exists, creating it if information technology does not, and upgrading it as necessary. Transactions are used to make certain the database is always in a sensible state.

This class makes information technology easy for ContentProvider implementations to defer opening and upgrading the database until beginning use, to avoid blocking application startup with long-running database upgrades.

For an example, encounter the NotePadProvider form in the NotePad sample application, in the samples/ directory of the SDK.

Note: this class assumes monotonically increasing version numbers for upgrades.

Note: the AutoCloseable interface was first added in the Build.VERSION_CODES.Q release.

Summary

Public constructors

SQLiteOpenHelper(Context context, Cord proper noun, SQLiteDatabase.CursorFactory factory, int version)

Create a helper object to create, open, and/or manage a database.

SQLiteOpenHelper(Context context, String proper name, SQLiteDatabase.CursorFactory manufactory, int version, DatabaseErrorHandler errorHandler)

Create a helper object to create, open up, and/or manage a database.

SQLiteOpenHelper(Context context, String name, int version, SQLiteDatabase.OpenParams openParams)

Create a helper object to create, open, and/or manage a database.

Public methods

void close()

Shut whatsoever open database object.

String getDatabaseName()

Return the proper name of the SQLite database being opened, as given to the constructor.

SQLiteDatabase getReadableDatabase()

Create and/or open a database.

SQLiteDatabase getWritableDatabase()

Create and/or open a database that will be used for reading and writing.

void onConfigure(SQLiteDatabase db)

Called when the database connection is being configured, to enable features such as write-ahead logging or foreign cardinal support.

abstract void onCreate(SQLiteDatabase db)

Called when the database is created for the first time.

void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion)

Called when the database needs to be downgraded.

void onOpen(SQLiteDatabase db)

Called when the database has been opened.

abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

Chosen when the database needs to be upgraded.

void setIdleConnectionTimeout(long idleConnectionTimeoutMs)

This method was deprecated in API level 29. Practice NOT Use this method. Encounter the javadoc of SQLiteDatabase.OpenParams.Architect#setIdleConnectionTimeout(long) for the details.

void setLookasideConfig(int slotSize, int slotCount)

Configures lookaside memory allocator

This method should be called from the constructor of the subclass, earlier opening the database, since lookaside memory configuration tin can only be changed when no connection is using it

SQLite default settings will be used, if this method isn't called.

void setOpenParams(SQLiteDatabase.OpenParams openParams)

Sets configuration parameters that are used for opening SQLiteDatabase.

void setWriteAheadLoggingEnabled(boolean enabled)

Enables or disables the use of write-ahead logging for the database.

Inherited methods

Public constructors

SQLiteOpenHelper

public SQLiteOpenHelper (Context context,                  String proper noun,                  SQLiteDatabase.CursorFactory mill,                  int version)

Create a helper object to create, open, and/or manage a database. This method always returns very quickly. The database is not actually created or opened until ane of getWritableDatabase() or getReadableDatabase() is called.

Parameters
context Context: to use for locating paths to the the database This value may be null.
name String: of the database file, or null for an in-memory database
factory SQLiteDatabase.CursorFactory: to use for creating cursor objects, or zip for the default
version int: number of the database (starting at 1); if the database is older, onUpgrade(SQLiteDatabase, int, int) will be used to upgrade the database; if the database is newer, onDowngrade(SQLiteDatabase, int, int) will be used to downgrade the database

SQLiteOpenHelper

public SQLiteOpenHelper (Context context,                  Cord proper name,                  SQLiteDatabase.CursorFactory factory,                  int version,                  DatabaseErrorHandler errorHandler)

Create a helper object to create, open, and/or manage a database. The database is non actually created or opened until one of getWritableDatabase() or getReadableDatabase() is chosen.

Accepts input param: a concrete instance of DatabaseErrorHandler to exist used to handle corruption when sqlite reports database corruption.

Parameters
context Context: to apply for locating paths to the the database This value may be zilch.
name String: of the database file, or aught for an in-memory database
factory SQLiteDatabase.CursorFactory: to apply for creating cursor objects, or aught for the default
version int: number of the database (starting at one); if the database is older, onUpgrade(SQLiteDatabase, int, int) volition be used to upgrade the database; if the database is newer, onDowngrade(SQLiteDatabase, int, int) will be used to downgrade the database
errorHandler DatabaseErrorHandler: the DatabaseErrorHandler to be used when sqlite reports database corruption, or nothing to apply the default error handler.

SQLiteOpenHelper

public SQLiteOpenHelper (Context context,                  String name,                  int version,                  SQLiteDatabase.OpenParams openParams)

Create a helper object to create, open up, and/or manage a database. This method always returns very speedily. The database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.

Parameters
context Context: to use for locating paths to the the database This value may be null.
proper name String: of the database file, or null for an in-retentiveness database
version int: number of the database (starting at 1); if the database is older, onUpgrade(SQLiteDatabase, int, int) will be used to upgrade the database; if the database is newer, onDowngrade(SQLiteDatabase, int, int) will be used to downgrade the database
openParams SQLiteDatabase.OpenParams: configuration parameters that are used for opening SQLiteDatabase. Delight annotation that SQLiteDatabase#CREATE_IF_NECESSARY flag volition always be set when the helper opens the database This value cannot be null.

Public methods

shut

public void close ()

Shut any open database object.

getDatabaseName

public String getDatabaseName ()

Render the name of the SQLite database existence opened, every bit given to the constructor.

Returns
Cord

getReadableDatabase

public SQLiteDatabase getReadableDatabase ()

Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full deejay, requires the database to exist opened read-simply. In that instance, a read-just database object will exist returned. If the problem is stock-still, a future telephone call to getWritableDatabase() may succeed, in which case the read-simply database object volition exist closed and the read/write object will exist returned in the future.

Like getWritableDatabase(), this method may take a long time to render, and then y'all should not call information technology from the application chief thread, including from ContentProvider.onCreate().

Returns
SQLiteDatabase a database object valid until getWritableDatabase() or close() is called.
Throws
SQLiteException if the database cannot be opened

getWritableDatabase

public SQLiteDatabase getWritableDatabase ()

Create and/or open a database that will be used for reading and writing. The get-go time this is called, the database volition be opened and onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and/or onOpen(SQLiteDatabase) will be called.

Once opened successfully, the database is buried, so you tin call this method every time you lot need to write to the database. (Make certain to call close() when you no longer demand the database.) Errors such every bit bad permissions or a full deejay may cause this method to fail, only future attempts may succeed if the problem is fixed.

Database upgrade may take a long time, you lot should not call this method from the application main thread, including from ContentProvider.onCreate().

Returns
SQLiteDatabase a read/write database object valid until close() is called
Throws
SQLiteException if the database cannot exist opened for writing

onConfigure

public void onConfigure (SQLiteDatabase db)

Called when the database connexion is being configured, to enable features such as write-alee logging or foreign key support.

This method is chosen before onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int), onDowngrade(SQLiteDatabase, int, int), or onOpen(SQLiteDatabase) are chosen. It should not modify the database except to configure the database connection as required.

This method should only phone call methods that configure the parameters of the database connectedness, such as SQLiteDatabase#enableWriteAheadLogging SQLiteDatabase#setForeignKeyConstraintsEnabled, SQLiteDatabase#setLocale, SQLiteDatabase#setMaximumSize, or executing PRAGMA statements.

Parameters
db SQLiteDatabase: The database.

onCreate

public abstract void onCreate (SQLiteDatabase db)

Called when the database is created for the kickoff time. This is where the creation of tables and the initial population of the tables should happen.

Parameters
db SQLiteDatabase: The database.

onDowngrade

public void onDowngrade (SQLiteDatabase db,                  int oldVersion,                  int newVersion)

Called when the database needs to be downgraded. This is strictly similar to onUpgrade(SQLiteDatabase, int, int) method, merely is called whenever electric current version is newer than requested i. All the same, this method is not abstract, and then information technology is non mandatory for a customer to implement it. If not overridden, default implementation will reject downgrade and throws SQLiteException

This method executes within a transaction. If an exception is thrown, all changes will automatically exist rolled dorsum.

Parameters
db SQLiteDatabase: The database.
oldVersion int: The one-time database version.
newVersion int: The new database version.

onOpen

public void onOpen (SQLiteDatabase db)

Called when the database has been opened. The implementation should check SQLiteDatabase#isReadOnly before updating the database.

This method is called after the database connection has been configured and afterward the database schema has been created, upgraded or downgraded as necessary. If the database connection must be configured in some style before the schema is created, upgraded, or downgraded, do information technology in onConfigure(SQLiteDatabase) instead.

Parameters
db SQLiteDatabase: The database.

onUpgrade

public abstract void onUpgrade (SQLiteDatabase db,                  int oldVersion,                  int newVersion)

Called when the database needs to be upgraded. The implementation should use this method to drop tables, add tables, or practice anything else it needs to upgrade to the new schema version.

The SQLite ALTER TABLE documentation tin be found here. If you add new columns you tin can utilize Alter TABLE to insert them into a live table. If you rename or remove columns you can use Modify Table to rename the old tabular array, then create the new table and then populate the new table with the contents of the quondam table.

This method executes inside a transaction. If an exception is thrown, all changes volition automatically exist rolled back.

Parameters
db SQLiteDatabase: The database.
oldVersion int: The quondam database version.
newVersion int: The new database version.

setIdleConnectionTimeout

public void setIdleConnectionTimeout (long idleConnectionTimeoutMs)

This method was deprecated in API level 29.
Practise Non Employ this method. See the javadoc of SQLiteDatabase.OpenParams.Builder#setIdleConnectionTimeout(long) for the details.

Sets the maximum number of milliseconds that SQLite connexion is allowed to be idle before information technology is closed and removed from the pool.

This method should be called from the constructor of the bracket, before opening the database

DO NOT USE this method. This feature has negative side furnishings that are very difficult to foresee. Encounter the javadoc of SQLiteDatabase.OpenParams.Architect#setIdleConnectionTimeout(long) for the details.

Parameters
idleConnectionTimeoutMs long: timeout in milliseconds. Utilise Long#MAX_VALUE value to allow unlimited idle connections. Value is 0 or greater

setLookasideConfig

public void setLookasideConfig (int slotSize,                  int slotCount)

Configures lookaside memory allocator

This method should be called from the constructor of the subclass, before opening the database, since lookaside memory configuration can but be changed when no connection is using it

SQLite default settings will exist used, if this method isn't called. Apply setLookasideConfig(0,0) to disable lookaside

Note: Provided slotSize/slotCount configuration is just a recommendation. The organisation may cull different values depending on a device, e.g. lookaside allocations tin can be disabled on low-RAM devices

Parameters
slotSize int: The size in bytes of each lookaside slot. Value is 0 or greater
slotCount int: The total number of lookaside memory slots per database connexion. Value is 0 or greater

setWriteAheadLoggingEnabled

public void setWriteAheadLoggingEnabled (boolean enabled)

Enables or disables the use of write-ahead logging for the database. Write-ahead logging cannot exist used with read-only databases and then the value of this flag is ignored if the database is opened read-only.

Parameters
enabled boolean: True if write-alee logging should be enabled, simulated if information technology should be disabled.