> Documentation index: https://developer.android.com/reference/llms.txt

Summary: [Ctors](https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.md.txt#pubctors) \| [Methods](https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.md.txt#pubmethods) \| [Inherited Methods](https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.md.txt#inhmethods)

# SQLiteOpenHelper

*** ** * ** ***


`
public


abstract
class
SQLiteOpenHelper
`


`

extends Object


`

`


implements

AutoCloseable


`

|---|---|
| [java.lang.Object](https://developer.android.com/reference/java/lang/Object.md.txt) ||
| ↳ | android.database.sqlite.SQLiteOpenHelper |

<br />

*** ** * ** ***

A helper class to manage database creation and version management.

You create a subclass implementing `onCreate(SQLiteDatabase)`, `onUpgrade(SQLiteDatabase, int, int)` and
optionally `onOpen(SQLiteDatabase)`, and this class takes care of opening the database
if it exists, creating it if it does not, and upgrading it as necessary.
Transactions are used to make sure the database is always in a sensible state.

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

For an example, see the NotePadProvider class 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.

<br />

## Summary

| ### Public constructors ||
|---|---|
| ` SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) ` Create a helper object to create, open, and/or manage a database. |
| ` SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) ` Create a helper object to create, open, 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() ` Close any open database object. |
| ` String` | ` getDatabaseName() ` Return the 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 key 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) ` Called when the database needs to be upgraded. |
| ` void` | ` setIdleConnectionTimeout(long idleConnectionTimeoutMs) ` *This method was deprecated in API level 29. DO NOT USE this method. See the javadoc of `SQLiteDatabase.OpenParams.Builder.setIdleConnectionTimeout(long)` for the details.* |
| ` void` | ` setLookasideConfig(int slotSize, int slotCount) ` Configures [lookaside memory allocator](https://sqlite.org/malloc.html#lookaside) This method should be called from the constructor of the subclass, before opening the database, since lookaside memory configuration 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

From class `

java.lang.Object

` `


Object` `
clone()
`

Creates and returns a copy of this object.


`


boolean` `
equals(Object obj)
`

Indicates whether some other object is "equal to" this one.


`


void` `
finalize()
`

Called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.


`


final

Class<?>` `
getClass()
`

Returns the runtime class of this `Object`.


`


int` `
hashCode()
`

Returns a hash code value for the object.


`


final

void` `
notify()
`

Wakes up a single thread that is waiting on this object's
monitor.


`


final

void` `
notifyAll()
`

Wakes up all threads that are waiting on this object's monitor.


`


String` `
toString()
`

Returns a string representation of the object.


`


final

void` `
wait(long timeoutMillis, int nanos)
`

Causes the current thread to wait until it is awakened, typically
by being *notified* or *interrupted*, or until a
certain amount of real time has elapsed.


`


final

void` `
wait(long timeoutMillis)
`

Causes the current thread to wait until it is awakened, typically
by being *notified* or *interrupted*, or until a
certain amount of real time has elapsed.


`


final

void` `
wait()
`

Causes the current thread to wait until it is awakened, typically
by being *notified* or *interrupted*.


From interface `

java.lang.AutoCloseable

` `
abstract


void` `
close()
`

Closes this resource, relinquishing any underlying resources.


## Public constructors

### SQLiteOpenHelper

```
public SQLiteOpenHelper (Context context, 
                String name, 
                SQLiteDatabase.CursorFactory factory, 
                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 one of `getWritableDatabase()` or
`getReadableDatabase()` is called.

<br />

| Parameters ||
|---|---|
| `context` | `Context`: to use for locating paths to the the database. This value may be `null`. <br /> |
| `name` | `String`: of the database file, or null for an in-memory database <br /> |
| `factory` | `SQLiteDatabase.CursorFactory`: to use for creating cursor objects, or null for the default <br /> |
| `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 <br /> |

### SQLiteOpenHelper

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

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

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

<br />

<br />

| Parameters ||
|---|---|
| `context` | `Context`: to use for locating paths to the the database. This value may be `null`. <br /> |
| `name` | `String`: of the database file, or null for an in-memory database <br /> |
| `factory` | `SQLiteDatabase.CursorFactory`: to use for creating cursor objects, or null for the default <br /> |
| `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 <br /> |
| `errorHandler` | `DatabaseErrorHandler`: the `DatabaseErrorHandler` to be used when sqlite reports database corruption, or null to use the default error handler. <br /> |

### SQLiteOpenHelper

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

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 one of `getWritableDatabase()` or
`getReadableDatabase()` is called.

<br />

| Parameters ||
|---|---|
| `context` | `Context`: to use for locating paths to the the database. This value may be `null`. <br /> |
| `name` | `String`: of the database file, or null for an in-memory database <br /> |
| `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 <br /> |
| `openParams` | `SQLiteDatabase.OpenParams`: configuration parameters that are used for opening `SQLiteDatabase`. Please note that `SQLiteDatabase.CREATE_IF_NECESSARY` flag will always be set when the helper opens the database. This value cannot be `null`. <br /> |

## Public methods

### close

```
public void close ()
```

Close any open database object.

<br />

### getDatabaseName

```
public String getDatabaseName ()
```

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

<br />

| Returns ||
|---|---|
| `String` | <br /> |

### 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 disk,
requires the database to be opened read-only. In that case, a read-only
database object will be returned. If the problem is fixed, a future call
to `getWritableDatabase()` may succeed, in which case the read-only
database object will be closed and the read/write object will be returned
in the future.

Like `getWritableDatabase()`, this method may
take a long time to return, so you should not call it from the
application main thread, including from
`ContentProvider.onCreate()`.

<br />

| Returns ||
|---|---|
| `SQLiteDatabase` | a database object valid until `getWritableDatabase()` or `close()` is called. <br /> |

| 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 first time this is called, the database will be opened and
`onCreate(SQLiteDatabase)`, `onUpgrade(SQLiteDatabase, int, int)` and/or `onOpen(SQLiteDatabase)` will be
called.

Once opened successfully, the database is cached, so you can
call this method every time you need to write to the database.
(Make sure to call `close()` when you no longer need the database.)
Errors such as bad permissions or a full disk may cause this method
to fail, but future attempts may succeed if the problem is fixed.

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

<br />

| Returns ||
|---|---|
| `SQLiteDatabase` | a read/write database object valid until `close()` is called <br /> |

| Throws ||
|---|---|
| `SQLiteException` | if the database cannot be opened for writing |

### onConfigure

```
public void onConfigure (SQLiteDatabase db)
```

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


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


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

<br />

<br />

| Parameters ||
|---|---|
| `db` | `SQLiteDatabase`: The database. <br /> |

### onCreate

```
public abstract void onCreate (SQLiteDatabase db)
```

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

<br />

| Parameters ||
|---|---|
| `db` | `SQLiteDatabase`: The database. <br /> |

### 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, but is called whenever current version is newer than requested one.
However, this method is not abstract, so it is not 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 be rolled back.

<br />

<br />

| Parameters ||
|---|---|
| `db` | `SQLiteDatabase`: The database. <br /> |
| `oldVersion` | `int`: The old database version. <br /> |
| `newVersion` | `int`: The new database version. <br /> |

### 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 after the database schema has been created, upgraded or downgraded as necessary.
If the database connection must be configured in some way before the schema
is created, upgraded, or downgraded, do it in `onConfigure(SQLiteDatabase)` instead.

<br />

<br />

| Parameters ||
|---|---|
| `db` | `SQLiteDatabase`: The database. <br /> |

### 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 do anything else it
needs to upgrade to the new schema version.


The SQLite ALTER TABLE documentation can be found
[here](http://sqlite.org/lang_altertable.html). If you add new columns
you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
you can use ALTER TABLE to rename the old table, then create the new table and then
populate the new table with the contents of the old table.


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


*Important:* You should NOT modify an existing migration step from version X to X+1
once a build has been released containing that migration step. If a migration step has an
error and it runs on a device, the step will NOT re-run itself in the future if a fix is made
to the migration step.

For example, suppose a migration step renames a database column from `foo` to
`bar` when the name should have been `baz`. If that migration step is released
in a build and runs on a user's device, the column will be renamed to `bar`. If the
developer subsequently edits this same migration step to change the name to `baz` as
intended, the user devices which have already run this step will still have the name
`bar`. Instead, a NEW migration step should be created to correct the error and rename
`bar` to `baz`, ensuring the error is corrected on devices which have already run
the migration step with the error.

<br />

<br />

| Parameters ||
|---|---|
| `db` | `SQLiteDatabase`: The database. <br /> |
| `oldVersion` | `int`: The old database version. <br /> |
| `newVersion` | `int`: The new database version. <br /> |

### setIdleConnectionTimeout

<br />

Deprecated in [API level
29](https://developer.android.com/guide/topics/manifest/uses-sdk-element#ApiLevels)

```
public void setIdleConnectionTimeout (long idleConnectionTimeoutMs)
```


**This method was deprecated
in API level 29.**   

DO NOT USE this method. See the javadoc of
`SQLiteDatabase.OpenParams.Builder.setIdleConnectionTimeout(long)`
for the details.

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

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

**DO NOT USE** this method.
This feature has negative side effects that are very hard to foresee.
See the javadoc of
`SQLiteDatabase.OpenParams.Builder.setIdleConnectionTimeout(long)`
for the details.

<br />

| Parameters ||
|---|---|
| `idleConnectionTimeoutMs` | `long`: timeout in milliseconds. Use `Long.MAX_VALUE` value to allow unlimited idle connections. Value is 0 or greater <br /> |

**See also:**

- `SQLiteDatabase.OpenParams.Builder.setIdleConnectionTimeout(long)`

### setLookasideConfig

```
public void setLookasideConfig (int slotSize, 
                int slotCount)
```

Configures [lookaside memory allocator](https://sqlite.org/malloc.html#lookaside)

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

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

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

<br />

| Parameters ||
|---|---|
| `slotSize` | `int`: The size in bytes of each lookaside slot. Value is 0 or greater <br /> |
| `slotCount` | `int`: The total number of lookaside memory slots per database connection. Value is 0 or greater <br /> |

### setOpenParams

```
public void setOpenParams (SQLiteDatabase.OpenParams openParams)
```

Sets configuration parameters that are used for opening `SQLiteDatabase`.

Please note that `SQLiteDatabase.CREATE_IF_NECESSARY` flag will always be set when
opening the database

<br />

| Parameters ||
|---|---|
| `openParams` | `SQLiteDatabase.OpenParams`: configuration parameters that are used for opening `SQLiteDatabase`. This value cannot be `null`. <br /> |

| Throws ||
|---|---|
| `IllegalStateException` | if the database is already open |

### setWriteAheadLoggingEnabled

```
public void setWriteAheadLoggingEnabled (boolean enabled)
```

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

Write-ahead logging cannot be used with read-only databases so the value of
this flag is ignored if the database is opened read-only.

<br />

| Parameters ||
|---|---|
| `enabled` | `boolean`: True if write-ahead logging should be enabled, false if it should be disabled. <br /> |

**See also:**

- `SQLiteDatabase.enableWriteAheadLogging()`