SQLiteDatabase
public
final
class
SQLiteDatabase
extends SQLiteClosable
java.lang.Object | ||
↳ | android.database.sqlite.SQLiteClosable | |
↳ | android.database.sqlite.SQLiteDatabase |
Exposes methods to manage a SQLite database.
SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks.
See the Notepad sample application in the SDK for an example of creating and managing a database.
Database names must be unique within an application, not across all applications.
Localized Collation - ORDER BY
In addition to SQLite's default BINARY
collator, Android supplies
two more, LOCALIZED
, which changes with the system's current locale,
and UNICODE
, which is the Unicode Collation Algorithm and not tailored
to the current locale.
Summary
Nested classes | |
---|---|
interface |
SQLiteDatabase.CursorFactory
Used to allow returning sub-classes of |
class |
SQLiteDatabase.OpenParams
Wrapper for configuration parameters that are used for opening |
Constants | |
---|---|
int |
CONFLICT_ABORT
When a constraint violation occurs,no ROLLBACK is executed so changes from prior commands within the same transaction are preserved. |
int |
CONFLICT_FAIL
When a constraint violation occurs, the command aborts with a return code SQLITE_CONSTRAINT. |
int |
CONFLICT_IGNORE
When a constraint violation occurs, the one row that contains the constraint violation is not inserted or changed. |
int |
CONFLICT_NONE
Use the following when no conflict action is specified. |
int |
CONFLICT_REPLACE
When a UNIQUE constraint violation occurs, the pre-existing rows that are causing the constraint violation are removed prior to inserting or updating the current row. |
int |
CONFLICT_ROLLBACK
When a constraint violation occurs, an immediate ROLLBACK occurs, thus ending the current transaction, and the command aborts with a return code of SQLITE_CONSTRAINT. |
int |
CREATE_IF_NECESSARY
Open flag: Flag for |
int |
ENABLE_WRITE_AHEAD_LOGGING
Open flag: Flag for |
String |
JOURNAL_MODE_DELETE
The |
String |
JOURNAL_MODE_MEMORY
The |
String |
JOURNAL_MODE_OFF
The |
String |
JOURNAL_MODE_PERSIST
The |
String |
JOURNAL_MODE_TRUNCATE
The |
String |
JOURNAL_MODE_WAL
The |
int |
MAX_SQL_CACHE_SIZE
Absolute max value that can be set by |
int |
NO_LOCALIZED_COLLATORS
Open flag: Flag for |
int |
OPEN_READONLY
Open flag: Flag for |
int |
OPEN_READWRITE
Open flag: Flag for |
int |
SQLITE_MAX_LIKE_PATTERN_LENGTH
Maximum Length Of A LIKE Or GLOB Pattern The pattern matching algorithm used in the default LIKE and GLOB implementation of SQLite can exhibit O(N^2) performance (where N is the number of characters in the pattern) for certain pathological cases. |
String |
SYNC_MODE_EXTRA
The |
String |
SYNC_MODE_FULL
In |
String |
SYNC_MODE_NORMAL
The |
String |
SYNC_MODE_OFF
In |
Public methods | |
---|---|
void
|
beginTransaction()
Begins a transaction in EXCLUSIVE mode. |
void
|
beginTransactionNonExclusive()
Begins a transaction in IMMEDIATE mode. |
void
|
beginTransactionReadOnly()
Begins a transaction in DEFERRED mode, with the android-specific constraint that the transaction is read-only. |
void
|
beginTransactionWithListener(SQLiteTransactionListener transactionListener)
Begins a transaction in EXCLUSIVE mode. |
void
|
beginTransactionWithListenerNonExclusive(SQLiteTransactionListener transactionListener)
Begins a transaction in IMMEDIATE mode. |
void
|
beginTransactionWithListenerReadOnly(SQLiteTransactionListener transactionListener)
Begins a transaction in read-only mode with a |
SQLiteStatement
|
compileStatement(String sql)
Compiles an SQL statement into a reusable pre-compiled statement object. |
static
SQLiteDatabase
|
create(SQLiteDatabase.CursorFactory factory)
Create a memory backed SQLite database. |
static
SQLiteDatabase
|
createInMemory(SQLiteDatabase.OpenParams openParams)
Create a memory backed SQLite database. |
SQLiteRawStatement
|
createRawStatement(String sql)
Return a |
int
|
delete(String table, String whereClause, String[] whereArgs)
Convenience method for deleting rows in the database. |
static
boolean
|
deleteDatabase(File file)
Deletes a database including its journal file and other auxiliary files that may have been created by the database engine. |
void
|
disableWriteAheadLogging()
This method disables the features enabled by |
boolean
|
enableWriteAheadLogging()
This method enables parallel execution of queries from multiple threads on the same database. |
void
|
endTransaction()
End a transaction. |
void
|
execPerConnectionSQL(String sql, Object[] bindArgs)
Execute the given SQL statement on all connections to this database. |
void
|
execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data. |
void
|
execSQL(String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE. |
static
String
|
findEditTable(String tables)
Finds the name of the first table, which is editable. |
List<Pair<String, String>>
|
getAttachedDbs()
Returns list of full pathnames of all attached databases including the main database by executing 'pragma database_list' on the database. |
long
|
getLastChangedRowCount()
Return the number of database rows that were inserted, updated, or deleted by the most recent SQL statement within the current transaction. |
long
|
getLastInsertRowId()
Return the "rowid" of the last row to be inserted on the current connection. |
long
|
getMaximumSize()
Returns the maximum size the database may grow to. |
long
|
getPageSize()
Returns the current database page size, in bytes. |
String
|
getPath()
Gets the path to the database file. |
Map<String, String>
|
getSyncedTables()
This method was deprecated in API level 15. This method no longer serves any useful purpose and has been deprecated. |
long
|
getTotalChangedRowCount()
Return the total number of database rows that have been inserted, updated, or deleted on the current connection since it was created. |
int
|
getVersion()
Gets the database version. |
boolean
|
inTransaction()
Returns true if the current thread has a transaction pending. |
long
|
insert(String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database. |
long
|
insertOrThrow(String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database. |
long
|
insertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm)
General method for inserting a row into the database. |
boolean
|
isDatabaseIntegrityOk()
Runs 'pragma integrity_check' on the given database (and all the attached databases) and returns true if the given database (and all its attached databases) pass integrity_check, false otherwise. |
boolean
|
isDbLockedByCurrentThread()
Returns true if the current thread is holding an active connection to the database. |
boolean
|
isDbLockedByOtherThreads()
This method was deprecated in API level 16. Always returns false. Do not use this method. |
boolean
|
isOpen()
Returns true if the database is currently open. |
boolean
|
isReadOnly()
Returns true if the database is opened as read only. |
boolean
|
isWriteAheadLoggingEnabled()
Returns true if write-ahead logging has been enabled for this database. |
void
|
markTableSyncable(String table, String deletedTable)
This method was deprecated in API level 15. This method no longer serves any useful purpose and has been deprecated. |
void
|
markTableSyncable(String table, String foreignKey, String updateTable)
This method was deprecated in API level 15. This method no longer serves any useful purpose and has been deprecated. |
boolean
|
needUpgrade(int newVersion)
Returns true if the new version code is greater than the current database version. |
static
SQLiteDatabase
|
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
Open the database according to the flags |
static
SQLiteDatabase
|
openDatabase(File path, SQLiteDatabase.OpenParams openParams)
Open the database according to the specified |
static
SQLiteDatabase
|
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)
Open the database according to the flags |
static
SQLiteDatabase
|
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY). |
static
SQLiteDatabase
|
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)
Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler). |
static
SQLiteDatabase
|
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY). |
Cursor
|
query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given URL, returning a |
Cursor
|
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given table, returning a |
Cursor
|
query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
Query the given URL, returning a |
Cursor
|
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Query the given table, returning a |
Cursor
|
queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
Query the given URL, returning a |
Cursor
|
queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given URL, returning a |
Cursor
|
rawQuery(String sql, String[] selectionArgs, CancellationSignal cancellationSignal)
Runs the provided SQL and returns a |
Cursor
|
rawQuery(String sql, String[] selectionArgs)
Runs the provided SQL and returns a |
Cursor
|
rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable, CancellationSignal cancellationSignal)
Runs the provided SQL and returns a cursor over the result set. |
Cursor
|
rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable)
Runs the provided SQL and returns a cursor over the result set. |
static
int
|
releaseMemory()
Attempts to release memory that SQLite holds but does not require to operate properly. |
long
|
replace(String table, String nullColumnHack, ContentValues initialValues)
Convenience method for replacing a row in the database. |
long
|
replaceOrThrow(String table, String nullColumnHack, ContentValues initialValues)
Convenience method for replacing a row in the database. |
void
|
setCustomAggregateFunction(String functionName, BinaryOperator<String> aggregateFunction)
Register a custom aggregate function that can be called from SQL expressions. |
void
|
setCustomScalarFunction(String functionName, UnaryOperator<String> scalarFunction)
Register a custom scalar function that can be called from SQL expressions. |
void
|
setForeignKeyConstraintsEnabled(boolean enable)
Sets whether foreign key constraints are enabled for the database. |
void
|
setLocale(Locale locale)
Sets the locale for this database. |
void
|
setLockingEnabled(boolean lockingEnabled)
This method was deprecated in API level 16. This method now does nothing. Do not use. |
void
|
setMaxSqlCacheSize(int cacheSize)
Sets the maximum size of the prepared-statement cache for this database. |
long
|
setMaximumSize(long numBytes)
Sets the maximum size the database will grow to. |
void
|
setPageSize(long numBytes)
Sets the database page size. |
void
|
setTransactionSuccessful()
Marks the current transaction as successful. |
void
|
setVersion(int version)
Sets the database version. |
String
|
toString()
Returns a string representation of the object. |
int
|
update(String table, ContentValues values, String whereClause, String[] whereArgs)
Convenience method for updating rows in the database. |
int
|
updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, int conflictAlgorithm)
Convenience method for updating rows in the database. |
void
|
validateSql(String sql, CancellationSignal cancellationSignal)
Verifies that a SQL SELECT statement is valid by compiling it. |
boolean
|
yieldIfContended()
This method was deprecated in API level 15. if the db is locked more than once (because of nested transactions) then the lock will not be yielded. Use yieldIfContendedSafely instead. |
boolean
|
yieldIfContendedSafely()
Temporarily end the transaction to let other threads run. |
boolean
|
yieldIfContendedSafely(long sleepAfterYieldDelay)
Temporarily end the transaction to let other threads run. |
Protected methods | |
---|---|
void
|
finalize()
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. |
void
|
onAllReferencesReleased()
Called when the last reference to the object was released by
a call to |
Inherited methods | |
---|---|
Constants
CONFLICT_ABORT
public static final int CONFLICT_ABORT
When a constraint violation occurs,no ROLLBACK is executed so changes from prior commands within the same transaction are preserved. This is the default behavior.
Constant Value: 2 (0x00000002)
CONFLICT_FAIL
public static final int CONFLICT_FAIL
When a constraint violation occurs, the command aborts with a return code SQLITE_CONSTRAINT. But any changes to the database that the command made prior to encountering the constraint violation are preserved and are not backed out.
Constant Value: 3 (0x00000003)
CONFLICT_IGNORE
public static final int CONFLICT_IGNORE
When a constraint violation occurs, the one row that contains the constraint violation is not inserted or changed. But the command continues executing normally. Other rows before and after the row that contained the constraint violation continue to be inserted or updated normally. No error is returned.
Constant Value: 4 (0x00000004)
CONFLICT_NONE
public static final int CONFLICT_NONE
Use the following when no conflict action is specified.
Constant Value: 0 (0x00000000)
CONFLICT_REPLACE
public static final int CONFLICT_REPLACE
When a UNIQUE constraint violation occurs, the pre-existing rows that are causing the constraint violation are removed prior to inserting or updating the current row. Thus the insert or update always occurs. The command continues executing normally. No error is returned. If a NOT NULL constraint violation occurs, the NULL value is replaced by the default value for that column. If the column has no default value, then the ABORT algorithm is used. If a CHECK constraint violation occurs then the IGNORE algorithm is used. When this conflict resolution strategy deletes rows in order to satisfy a constraint, it does not invoke delete triggers on those rows. This behavior might change in a future release.
Constant Value: 5 (0x00000005)
CONFLICT_ROLLBACK
public static final int CONFLICT_ROLLBACK
When a constraint violation occurs, an immediate ROLLBACK occurs, thus ending the current transaction, and the command aborts with a return code of SQLITE_CONSTRAINT. If no transaction is active (other than the implied transaction that is created on every command) then this algorithm works the same as ABORT.
Constant Value: 1 (0x00000001)
CREATE_IF_NECESSARY
public static final int CREATE_IF_NECESSARY
Open flag: Flag for openDatabase(File, OpenParams)
to create the database file if it does not
already exist.
Constant Value: 268435456 (0x10000000)
ENABLE_WRITE_AHEAD_LOGGING
public static final int ENABLE_WRITE_AHEAD_LOGGING
Open flag: Flag for openDatabase(File, OpenParams)
to open the database file with
write-ahead logging enabled by default. Using this flag is more efficient
than calling enableWriteAheadLogging()
.
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.
See also:
Constant Value: 536870912 (0x20000000)
JOURNAL_MODE_DELETE
public static final String JOURNAL_MODE_DELETE
The DELETE
journaling mode is the normal behavior. In the DELETE mode, the rollback
journal is deleted at the conclusion of each transaction.
See here for more details.
Constant Value: "DELETE"
JOURNAL_MODE_MEMORY
public static final String JOURNAL_MODE_MEMORY
The MEMORY
journaling mode stores the rollback journal in volatile RAM.
This saves disk I/O but at the expense of database safety and integrity. If the application
using SQLite crashes in the middle of a transaction when the MEMORY journaling mode is set,
then the database file will very likely go corrupt.
See here for more details.
Constant Value: "MEMORY"
JOURNAL_MODE_OFF
public static final String JOURNAL_MODE_OFF
The OFF
journaling mode disables the rollback journal completely. No rollback journal
is ever created and hence there is never a rollback journal to delete. The OFF journaling
mode disables the atomic commit and rollback capabilities of SQLite. The ROLLBACK command
behaves in an undefined way thus applications must avoid using the ROLLBACK command.
If the application crashes in the middle of a transaction, then the database file will very
likely go corrupt.
See here for more details.
Constant Value: "OFF"
JOURNAL_MODE_PERSIST
public static final String JOURNAL_MODE_PERSIST
The PERSIST
journaling mode prevents the rollback journal from being deleted at the
end of each transaction. Instead, the header of the journal is overwritten with zeros.
This will prevent other database connections from rolling the journal back.
This mode is useful as an optimization on platforms where deleting or truncating a file is
much more expensive than overwriting the first block of a file with zeros.
See here for more details.
Constant Value: "PERSIST"
JOURNAL_MODE_TRUNCATE
public static final String JOURNAL_MODE_TRUNCATE
The TRUNCATE
journaling mode commits transactions by truncating the rollback journal
to zero-length instead of deleting it. On many systems, truncating a file is much faster than
deleting the file since the containing directory does not need to be changed.
See here for more details.
Constant Value: "TRUNCATE"
JOURNAL_MODE_WAL
public static final String JOURNAL_MODE_WAL
The WAL
journaling mode uses a write-ahead log instead of a rollback journal to
implement transactions. The WAL journaling mode is persistent; after being set it stays
in effect across multiple database connections and after closing and reopening the database.
Performance Considerations:
This mode is recommended when the goal is to improve write performance or parallel read/write
performance. However, it is important to note that WAL introduces checkpoints which commit
all transactions that have not been synced to the database thus to maximize read performance
and lower checkpointing cost a small journal size is recommended. However, other modes such
as DELETE
will not perform checkpoints, so it is a trade off that needs to be
considered as part of the decision of which journal mode to use.
See here for more details.
Constant Value: "WAL"
MAX_SQL_CACHE_SIZE
public static final int MAX_SQL_CACHE_SIZE
Absolute max value that can be set by setMaxSqlCacheSize(int)
.
Each prepared-statement is between 1K - 6K, depending on the complexity of the
SQL statement & schema. A large SQL cache may use a significant amount of memory.
Constant Value: 100 (0x00000064)
NO_LOCALIZED_COLLATORS
public static final int NO_LOCALIZED_COLLATORS
Open flag: Flag for openDatabase(File, OpenParams)
to open the database without support for
localized collators.
This causes the collator LOCALIZED
not to be created.
You must be consistent when using this flag to use the setting the database was
created with. If this is set, setLocale(Locale)
will do nothing.
Constant Value: 16 (0x00000010)
OPEN_READONLY
public static final int OPEN_READONLY
Open flag: Flag for openDatabase(File, OpenParams)
to open the database for reading only.
This is the only reliable way to open a database if the disk may be full.
Constant Value: 1 (0x00000001)
OPEN_READWRITE
public static final int OPEN_READWRITE
Open flag: Flag for openDatabase(File, OpenParams)
to open the database for reading and writing.
If the disk is full, this may fail even before you actually write anything.
Note that the value of this flag is 0, so it is the default.
Constant Value: 0 (0x00000000)
SQLITE_MAX_LIKE_PATTERN_LENGTH
public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH
Maximum Length Of A LIKE Or GLOB Pattern The pattern matching algorithm used in the default LIKE and GLOB implementation of SQLite can exhibit O(N^2) performance (where N is the number of characters in the pattern) for certain pathological cases. To avoid denial-of-service attacks the length of the LIKE or GLOB pattern is limited to SQLITE_MAX_LIKE_PATTERN_LENGTH bytes. The default value of this limit is 50000. A modern workstation can evaluate even a pathological LIKE or GLOB pattern of 50000 bytes relatively quickly. The denial of service problem only comes into play when the pattern length gets into millions of bytes. Nevertheless, since most useful LIKE or GLOB patterns are at most a few dozen bytes in length, cautious application developers may want to reduce this parameter to something in the range of a few hundred if they know that external users are able to generate arbitrary patterns.
Constant Value: 50000 (0x0000c350)
SYNC_MODE_EXTRA
public static final String SYNC_MODE_EXTRA
The EXTRA
sync mode is like FULL
sync mode with the addition that the
directory containing a rollback journal is synced after that journal is unlinked to commit a
transaction in DELETE
journal mode.
EXTRA
provides additional durability if the commit is followed closely by a
power loss.
See here for more details.
Constant Value: "EXTRA"
SYNC_MODE_FULL
public static final String SYNC_MODE_FULL
In FULL
sync mode the SQLite database engine will use the xSync method of the VFS
to ensure that all content is safely written to the disk surface prior to continuing.
This ensures that an operating system crash or power failure will not corrupt the database.
FULL
is very safe, but it is also slower.
FULL
is the most commonly used synchronous setting when not in WAL mode.
See here for more details.
Constant Value: "FULL"
SYNC_MODE_NORMAL
public static final String SYNC_MODE_NORMAL
The NORMAL
sync mode, the SQLite database engine will still sync at the most critical
moments, but less often than in FULL
mode. There is a very small chance that a
power failure at the wrong time could corrupt the database in DELETE
journal mode on
an older filesystem.
WAL
journal mode is safe from corruption with NORMAL
sync mode, and probably
DELETE
sync mode is safe too on modern filesystems. WAL mode is always consistent
with NORMAL
sync mode, but WAL mode does lose durability. A transaction committed in
WAL mode with NORMAL
might roll back following a power loss or system crash.
Transactions are durable across application crashes regardless of the synchronous setting
or journal mode.
The NORMAL
sync mode is a good choice for most applications running in WAL mode.
Caveat: Even though this sync mode is safe Be careful when using NORMAL
sync mode
when dealing with data dependencies between multiple databases, unless those databases use
the same durability or are somehow synced, there could be corruption.
See here for more details.
Constant Value: "NORMAL"
SYNC_MODE_OFF
public static final String SYNC_MODE_OFF
In OFF
sync mode SQLite continues without syncing as soon as it has handed data off
to the operating system. If the application running SQLite crashes, the data will be safe,
but the database might become corrupted if the operating system crashes or the computer loses
power before that data has been written to the disk surface. On the other hand, commits can
be orders of magnitude faster with synchronous OFF
.
See here for more details.
Constant Value: "OFF"
Public methods
beginTransaction
public void beginTransaction ()
Begins a transaction in EXCLUSIVE mode.
Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Here is the standard idiom for transactions:
db.beginTransaction(); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }
beginTransactionNonExclusive
public void beginTransactionNonExclusive ()
Begins a transaction in IMMEDIATE mode. Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Here is the standard idiom for transactions:
db.beginTransactionNonExclusive(); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }
beginTransactionReadOnly
public void beginTransactionReadOnly ()
Begins a transaction in DEFERRED mode, with the android-specific constraint that the transaction is read-only. The database may not be modified inside a read-only transaction.
Read-only transactions may run concurrently with other read-only transactions, and if the
database is in WAL mode, they may also run concurrently with IMMEDIATE or EXCLUSIVE
transactions. The temp
schema may be modified during a read-only transaction;
if the transaction is setTransactionSuccessful()
, modifications to temp tables may
be visible to some subsequent transactions.
Transactions can be nested. However, the behavior of the transaction is not altered by nested transactions. A nested transaction may be any of the three transaction types but if the outermost type is read-only then nested transactions remain read-only, regardless of how they are started.
Here is the standard idiom for read-only transactions:
db.beginTransactionReadOnly(); try { ... } finally { db.endTransaction(); }
beginTransactionWithListener
public void beginTransactionWithListener (SQLiteTransactionListener transactionListener)
Begins a transaction in EXCLUSIVE mode.
Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Here is the standard idiom for transactions:
db.beginTransactionWithListener(listener); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }
Parameters | |
---|---|
transactionListener |
SQLiteTransactionListener : listener that should be notified when the transaction begins,
commits, or is rolled back, either explicitly or by a call to
yieldIfContendedSafely() .
This value may be null . |
beginTransactionWithListenerNonExclusive
public void beginTransactionWithListenerNonExclusive (SQLiteTransactionListener transactionListener)
Begins a transaction in IMMEDIATE mode. Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Here is the standard idiom for transactions:
db.beginTransactionWithListenerNonExclusive(listener); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }
Parameters | |
---|---|
transactionListener |
SQLiteTransactionListener : listener that should be notified when the
transaction begins, commits, or is rolled back, either
explicitly or by a call to yieldIfContendedSafely() .
This value may be null . |
beginTransactionWithListenerReadOnly
public void beginTransactionWithListenerReadOnly (SQLiteTransactionListener transactionListener)
Begins a transaction in read-only mode with a SQLiteTransactionListener
listener.
The database may not be updated inside a read-only transaction.
Transactions can be nested. However, the behavior of the transaction is not altered by nested transactions. A nested transaction may be any of the three transaction types but if the outermost type is read-only then nested transactions remain read-only, regardless of how they are started.
Here is the standard idiom for read-only transactions:
db.beginTransactionWightListenerReadOnly(listener); try { ... } finally { db.endTransaction(); }
Parameters | |
---|---|
transactionListener |
SQLiteTransactionListener : This value may be null . |
compileStatement
public SQLiteStatement compileStatement (String sql)
Compiles an SQL statement into a reusable pre-compiled statement object.
The parameters are identical to execSQL(java.lang.String)
. You may put ?s in the
statement and fill in those values with SQLiteProgram#bindString
and SQLiteProgram#bindLong
each time you want to run the
statement. Statements may not return result sets larger than 1x1.
No two threads should be using the same SQLiteStatement
at the same time.
Parameters | |
---|---|
sql |
String : The raw SQL statement, may contain ? for unknown values to be
bound later. |
Returns | |
---|---|
SQLiteStatement |
A pre-compiled SQLiteStatement object. Note that
SQLiteStatement s are not synchronized, see the documentation for more details. |
Throws | |
---|---|
SQLException |
create
public static SQLiteDatabase create (SQLiteDatabase.CursorFactory factory)
Create a memory backed SQLite database. Its contents will be destroyed when the database is closed.
Sets the locale of the database to the system's current locale.
Call setLocale(Locale)
if you would like something else.
Parameters | |
---|---|
factory |
SQLiteDatabase.CursorFactory : an optional factory class that is called to instantiate a
cursor when query is called
This value may be null . |
Returns | |
---|---|
SQLiteDatabase |
a SQLiteDatabase instance
This value cannot be null . |
Throws | |
---|---|
SQLiteException |
if the database cannot be created |
createInMemory
public static SQLiteDatabase createInMemory (SQLiteDatabase.OpenParams openParams)
Create a memory backed SQLite database. Its contents will be destroyed when the database is closed.
Sets the locale of the database to the system's current locale.
Call setLocale(Locale)
if you would like something else.
Parameters | |
---|---|
openParams |
SQLiteDatabase.OpenParams : configuration parameters that are used for opening SQLiteDatabase
This value cannot be null . |
Returns | |
---|---|
SQLiteDatabase |
a SQLiteDatabase instance
This value cannot be null . |
Throws | |
---|---|
SQLException |
if the database cannot be created |
createRawStatement
public SQLiteRawStatement createRawStatement (String sql)
Return a SQLiteRawStatement
connected to the database. A transaction must be in
progress or an exception will be thrown. The resulting object will be closed automatically
when the current transaction closes.
Parameters | |
---|---|
sql |
String : The SQL string to be compiled into a prepared statement.
This value cannot be null . |
Returns | |
---|---|
SQLiteRawStatement |
A SQLiteRawStatement holding the compiled SQL.
This value cannot be null . |
Throws | |
---|---|
IllegalStateException |
if a transaction is not in progress. |
SQLiteException |
if the SQL cannot be compiled. |
delete
public int delete (String table, String whereClause, String[] whereArgs)
Convenience method for deleting rows in the database.
Parameters | |
---|---|
table |
String : the table to delete from
This value cannot be null . |
whereClause |
String : the optional WHERE clause to apply when deleting.
Passing null will delete all rows. |
whereArgs |
String : You may include ?s in the where clause, which
will be replaced by the values from whereArgs. The values
will be bound as Strings. If whereClause is null or does not
contain ?s then whereArgs may be null. |
Returns | |
---|---|
int |
the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause. |
deleteDatabase
public static boolean deleteDatabase (File file)
Deletes a database including its journal file and other auxiliary files that may have been created by the database engine.
Parameters | |
---|---|
file |
File : The database file path.
This value cannot be null . |
Returns | |
---|---|
boolean |
True if the database was successfully deleted. |
disableWriteAheadLogging
public void disableWriteAheadLogging ()
This method disables the features enabled by enableWriteAheadLogging()
.
Throws | |
---|---|
IllegalStateException |
if there are transactions in progress at the time this method is called. WAL mode can only be changed when there are no transactions in progress. |
See also:
enableWriteAheadLogging
public boolean enableWriteAheadLogging ()
This method enables parallel execution of queries from multiple threads on the same database. It does this by opening multiple connections to the database and using a different database connection for each query. The database journal mode is also changed to enable writes to proceed concurrently with reads.
When write-ahead logging is not enabled (the default), it is not possible for reads and writes to occur on the database at the same time. Before modifying the database, the writer implicitly acquires an exclusive lock on the database which prevents readers from accessing the database until the write is completed.
In contrast, when write-ahead logging is enabled (by calling this method), write operations occur in a separate log file which allows reads to proceed concurrently. While a write is in progress, readers on other threads will perceive the state of the database as it was before the write began. When the write completes, readers on other threads will then perceive the new state of the database.
It is a good idea to enable write-ahead logging whenever a database will be concurrently accessed and modified by multiple threads at the same time. However, write-ahead logging uses significantly more memory than ordinary journaling because there are multiple connections to the same database. So if a database will only be used by a single thread, or if optimizing concurrency is not very important, then write-ahead logging should be disabled.
After calling this method, execution of queries in parallel is enabled as long as
the database remains open. To disable execution of queries in parallel, either
call disableWriteAheadLogging()
or close the database and reopen it.
The maximum number of connections used to execute queries in parallel is dependent upon the device memory and possibly other properties.
If a query is part of a transaction, then it is executed on the same database handle the transaction was begun.
Writers should use beginTransactionNonExclusive()
or
beginTransactionWithListenerNonExclusive(android.database.sqlite.SQLiteTransactionListener)
to start a transaction. Non-exclusive mode allows database file to be in readable
by other threads executing queries.
If the database has any attached databases, then execution of queries in parallel is NOT
possible. Likewise, write-ahead logging is not supported for read-only databases
or memory databases. In such cases, enableWriteAheadLogging()
returns false.
The best way to enable write-ahead logging is to pass the
ENABLE_WRITE_AHEAD_LOGGING
flag to openDatabase(File, OpenParams)
. This is
more efficient than calling enableWriteAheadLogging()
.
SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING,
myDatabaseErrorHandler);
Another way to enable write-ahead logging is to call enableWriteAheadLogging()
after opening the database.
SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
SQLiteDatabase.CREATE_IF_NECESSARY, myDatabaseErrorHandler);
db.enableWriteAheadLogging();
See also SQLite Write-Ahead Logging for more details about how write-ahead logging works.
Returns | |
---|---|
boolean |
True if write-ahead logging is enabled. |
Throws | |
---|---|
IllegalStateException |
if there are transactions in progress at the time this method is called. WAL mode can only be changed when there are no transactions in progress. |
endTransaction
public void endTransaction ()
End a transaction. See beginTransaction for notes about how to use this and when transactions are committed and rolled back.
execPerConnectionSQL
public void execPerConnectionSQL (String sql, Object[] bindArgs)
Execute the given SQL statement on all connections to this database.
This statement will be immediately executed on all existing connections, and will be automatically executed on all future connections.
Some example usages are changes like PRAGMA trusted_schema=OFF
or
functions like SELECT icu_load_collation()
. If you execute these
statements using execSQL(String)
then they will only apply to a single
database connection; using this method will ensure that they are
uniformly applied to all current and future connections.
Parameters | |
---|---|
sql |
String : The SQL statement to be executed. Multiple statements
separated by semicolons are not supported.
This value cannot be null . |
bindArgs |
Object : The arguments that should be bound to the SQL statement.
This value may be null . |
Throws | |
---|---|
SQLException |
execSQL
public void execSQL (String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
It has no means to return any data (such as the number of affected rows).
Instead, you're encouraged to use insert(java.lang.String, java.lang.String, android.content.ContentValues)
,
update(java.lang.String, android.content.ContentValues, java.lang.String, java.lang.String[])
, et al, when possible.
When using enableWriteAheadLogging()
, journal_mode is
automatically managed by this class. So, do not set journal_mode
using "PRAGMA journal_mode'enableWriteAheadLogging()
Note that PRAGMA
values which apply on a per-connection basis
should not be configured using this method; you should instead
use execPerConnectionSQL(String, Object)
to ensure that they are uniformly
applied to all current and future connections.
Parameters | |
---|---|
sql |
String : the SQL statement to be executed. Multiple statements separated by semicolons are
not supported. |
Throws | |
---|---|
SQLException |
if the SQL string is invalid |
execSQL
public void execSQL (String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
For INSERT statements, use any of the following instead.
insert(java.lang.String, java.lang.String, android.content.ContentValues)
insertOrThrow(java.lang.String, java.lang.String, android.content.ContentValues)
insertWithOnConflict(java.lang.String, java.lang.String, android.content.ContentValues, int)
For UPDATE statements, use any of the following instead.
update(java.lang.String, android.content.ContentValues, java.lang.String, java.lang.String[])
updateWithOnConflict(java.lang.String, android.content.ContentValues, java.lang.String, java.lang.String[], int)
For DELETE statements, use any of the following instead.
For example, the following are good candidates for using this method:
- ALTER TABLE
- CREATE or DROP table / trigger / view / index / virtual table
- REINDEX
- RELEASE
- SAVEPOINT
- PRAGMA that returns no data
When using enableWriteAheadLogging()
, journal_mode is
automatically managed by this class. So, do not set journal_mode
using "PRAGMA journal_mode'enableWriteAheadLogging()
Note that PRAGMA
values which apply on a per-connection basis
should not be configured using this method; you should instead
use execPerConnectionSQL(String, Object)
to ensure that they are uniformly
applied to all current and future connections.
Parameters | |
---|---|
sql |
String : the SQL statement to be executed. Multiple statements separated by semicolons are
not supported.
This value cannot be null . |
bindArgs |
Object : only byte[], String, Long and Double are supported in bindArgs.
This value cannot be null . |
Throws | |
---|---|
SQLException |
if the SQL string is invalid |
findEditTable
public static String findEditTable (String tables)
Finds the name of the first table, which is editable.
Parameters | |
---|---|
tables |
String : a list of tables |
Returns | |
---|---|
String |
the first table listed |
getAttachedDbs
public List<Pair<String, String>> getAttachedDbs ()
Returns list of full pathnames of all attached databases including the main database by executing 'pragma database_list' on the database.
Returns | |
---|---|
List<Pair<String, String>> |
ArrayList of pairs of (database name, database file path) or null if the database is not open. |
getLastChangedRowCount
public long getLastChangedRowCount ()
Return the number of database rows that were inserted, updated, or deleted by the most recent SQL statement within the current transaction.
Returns | |
---|---|
long |
The number of rows changed by the most recent sql statement |
Throws | |
---|---|
IllegalStateException |
if there is no current transaction. |
See also:
getLastInsertRowId
public long getLastInsertRowId ()
Return the "rowid" of the last row to be inserted on the current connection. This method must
only be called when inside a transaction. IllegalStateException
is thrown if the
method is called outside a transaction. If the function is called before any inserts in the
current transaction, the value returned will be from a previous transaction, which may be
from a different thread. If no inserts have occurred on the current connection, the function
returns 0. See the SQLite documentation for the specific details.
Returns | |
---|---|
long |
The ROWID of the last row to be inserted under this connection. |
Throws | |
---|---|
IllegalStateException |
if there is no current transaction. |
See also:
getMaximumSize
public long getMaximumSize ()
Returns the maximum size the database may grow to.
Returns | |
---|---|
long |
the new maximum database size |
getPageSize
public long getPageSize ()
Returns the current database page size, in bytes.
Returns | |
---|---|
long |
the database page size, in bytes |
getPath
public String getPath ()
Gets the path to the database file.
Returns | |
---|---|
String |
The path to the database file. |
getSyncedTables
public Map<String, String> getSyncedTables ()
This method was deprecated
in API level 15.
This method no longer serves any useful purpose and has been deprecated.
Deprecated.
Returns | |
---|---|
Map<String, String> |
getTotalChangedRowCount
public long getTotalChangedRowCount ()
Return the total number of database rows that have been inserted, updated, or deleted on
the current connection since it was created. Due to Android's internal management of
SQLite connections, the value may, or may not, include changes made in earlier
transactions. Best practice is to compare values returned within a single transaction.
database.beginTransaction();
try {
long initialValue = database.getTotalChangedRowCount();
// Execute SQL statements
long changedRows = database.getTotalChangedRowCount() - initialValue;
// changedRows counts the total number of rows updated in the transaction.
} finally {
database.endTransaction();
}
Returns | |
---|---|
long |
The number of rows changed on the current connection. |
Throws | |
---|---|
IllegalStateException |
if there is no current transaction. |
See also:
getVersion
public int getVersion ()
Gets the database version.
Returns | |
---|---|
int |
the database version |
inTransaction
public boolean inTransaction ()
Returns true if the current thread has a transaction pending.
Returns | |
---|---|
boolean |
True if the current thread is in a transaction. |
insert
public long insert (String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database.
Parameters | |
---|---|
table |
String : the table to insert the row into
This value cannot be null . |
nullColumnHack |
String : optional; may be null .
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided values is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your values is empty. |
values |
ContentValues : this map contains the initial column values for the
row. The keys should be the column names and the values the
column values
This value may be null . |
Returns | |
---|---|
long |
the row ID of the newly inserted row, or -1 if an error occurred |
insertOrThrow
public long insertOrThrow (String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database.
Parameters | |
---|---|
table |
String : the table to insert the row into
This value cannot be null . |
nullColumnHack |
String : optional; may be null .
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided values is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your values is empty. |
values |
ContentValues : this map contains the initial column values for the
row. The keys should be the column names and the values the
column values
This value may be null . |
Returns | |
---|---|
long |
the row ID of the newly inserted row, or -1 if an error occurred |
Throws | |
---|---|
|
android.database.SQLException |
SQLException |
insertWithOnConflict
public long insertWithOnConflict (String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm)
General method for inserting a row into the database.
Parameters | |
---|---|
table |
String : the table to insert the row into
This value cannot be null . |
nullColumnHack |
String : optional; may be null .
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided initialValues is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your initialValues is empty. |
initialValues |
ContentValues : this map contains the initial column values for the
row. The keys should be the column names and the values the
column values
This value may be null . |
conflictAlgorithm |
int : for insert conflict resolver |
Returns | |
---|---|
long |
the row ID of the newly inserted row OR -1 if either the
input parameter conflictAlgorithm = CONFLICT_IGNORE
or an error occurred. |
isDatabaseIntegrityOk
public boolean isDatabaseIntegrityOk ()
Runs 'pragma integrity_check' on the given database (and all the attached databases) and returns true if the given database (and all its attached databases) pass integrity_check, false otherwise.
If the result is false, then this method logs the errors reported by the integrity_check command execution.
Note that 'pragma integrity_check' on a database can take a long time.
Returns | |
---|---|
boolean |
true if the given database (and all its attached databases) pass integrity_check, false otherwise. |
isDbLockedByCurrentThread
public boolean isDbLockedByCurrentThread ()
Returns true if the current thread is holding an active connection to the database.
The name of this method comes from a time when having an active connection to the database meant that the thread was holding an actual lock on the database. Nowadays, there is no longer a true "database lock" although threads may block if they cannot acquire a database connection to perform a particular operation.
Returns | |
---|---|
boolean |
True if the current thread is holding an active connection to the database. |
isDbLockedByOtherThreads
public boolean isDbLockedByOtherThreads ()
This method was deprecated
in API level 16.
Always returns false. Do not use this method.
Always returns false.
There is no longer the concept of a database lock, so this method always returns false.
Returns | |
---|---|
boolean |
False. |
isOpen
public boolean isOpen ()
Returns true if the database is currently open.
Returns | |
---|---|
boolean |
True if the database is currently open (has not been closed). |
isReadOnly
public boolean isReadOnly ()
Returns true if the database is opened as read only.
Returns | |
---|---|
boolean |
True if database is opened as read only. |
isWriteAheadLoggingEnabled
public boolean isWriteAheadLoggingEnabled ()
Returns true if write-ahead logging has been enabled for this database.
Returns | |
---|---|
boolean |
True if write-ahead logging has been enabled for this database. |
markTableSyncable
public void markTableSyncable (String table, String deletedTable)
This method was deprecated
in API level 15.
This method no longer serves any useful purpose and has been deprecated.
Mark this table as syncable. When an update occurs in this table the _sync_dirty field will be set to ensure proper syncing operation.
Parameters | |
---|---|
table |
String : the table to mark as syncable |
deletedTable |
String : The deleted table that corresponds to the
syncable table |
markTableSyncable
public void markTableSyncable (String table, String foreignKey, String updateTable)
This method was deprecated
in API level 15.
This method no longer serves any useful purpose and has been deprecated.
Mark this table as syncable, with the _sync_dirty residing in another table. When an update occurs in this table the _sync_dirty field of the row in updateTable with the _id in foreignKey will be set to ensure proper syncing operation.
Parameters | |
---|---|
table |
String : an update on this table will trigger a sync time removal |
foreignKey |
String : this is the column in table whose value is an _id in
updateTable |
updateTable |
String : this is the table that will have its _sync_dirty |
needUpgrade
public boolean needUpgrade (int newVersion)
Returns true if the new version code is greater than the current database version.
Parameters | |
---|---|
newVersion |
int : The new version code. |
Returns | |
---|---|
boolean |
True if the new version code is greater than the current database version. |
openDatabase
public static SQLiteDatabase openDatabase (String path, SQLiteDatabase.CursorFactory factory, int flags)
Open the database according to the flags OPEN_READWRITE
OPEN_READONLY
CREATE_IF_NECESSARY
and/or NO_LOCALIZED_COLLATORS
.
Sets the locale of the database to the system's current locale.
Call setLocale(Locale)
if you would like something else.
Parameters | |
---|---|
path |
String : to database file to open and/or create
This value cannot be null . |
factory |
SQLiteDatabase.CursorFactory : an optional factory class that is called to instantiate a
cursor when query is called, or null for default |
flags |
int : to control database access mode
Value is either 0 or a combination of OPEN_READWRITE , OPEN_READONLY , CREATE_IF_NECESSARY , NO_LOCALIZED_COLLATORS , and ENABLE_WRITE_AHEAD_LOGGING |
Returns | |
---|---|
SQLiteDatabase |
the newly opened database |
Throws | |
---|---|
SQLiteException |
if the database cannot be opened |
openDatabase
public static SQLiteDatabase openDatabase (File path, SQLiteDatabase.OpenParams openParams)
Open the database according to the specified parameters
Parameters | |
---|---|
path |
File : path to database file to open and/or create.
Important: The file should be constructed either from an absolute path or
by using |
openParams |
SQLiteDatabase.OpenParams : configuration parameters that are used for opening SQLiteDatabase
This value cannot be null . |
Returns | |
---|---|
SQLiteDatabase |
the newly opened database |
Throws | |
---|---|
SQLiteException |
if the database cannot be opened |
openDatabase
public static SQLiteDatabase openDatabase (String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)
Open the database according to the flags OPEN_READWRITE
OPEN_READONLY
CREATE_IF_NECESSARY
and/or NO_LOCALIZED_COLLATORS
.
Sets the locale of the database to the system's current locale.
Call setLocale(Locale)
if you would like something else.
Accepts input param: a concrete instance of DatabaseErrorHandler
to be
used to handle corruption when sqlite reports database corruption.
Parameters | |
---|---|
path |
String : to database file to open and/or create
This value cannot be null . |
factory |
SQLiteDatabase.CursorFactory : an optional factory class that is called to instantiate a
cursor when query is called, or null for default |
flags |
int : to control database access mode
Value is either 0 or a combination of OPEN_READWRITE , OPEN_READONLY , CREATE_IF_NECESSARY , NO_LOCALIZED_COLLATORS , and ENABLE_WRITE_AHEAD_LOGGING |
errorHandler |
DatabaseErrorHandler : the DatabaseErrorHandler obj to be used to handle corruption
when sqlite reports database corruption
This value may be null . |
Returns | |
---|---|
SQLiteDatabase |
the newly opened database |
Throws | |
---|---|
SQLiteException |
if the database cannot be opened |
openOrCreateDatabase
public static SQLiteDatabase openOrCreateDatabase (File file, SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
Parameters | |
---|---|
file |
File : This value cannot be null . |
factory |
SQLiteDatabase.CursorFactory : This value may be null . |
Returns | |
---|---|
SQLiteDatabase |
openOrCreateDatabase
public static SQLiteDatabase openOrCreateDatabase (String path, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)
Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
Parameters | |
---|---|
path |
String : This value cannot be null . |
factory |
SQLiteDatabase.CursorFactory : This value may be null . |
errorHandler |
DatabaseErrorHandler : This value may be null . |
Returns | |
---|---|
SQLiteDatabase |
openOrCreateDatabase
public static SQLiteDatabase openOrCreateDatabase (String path, SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
Parameters | |
---|---|
path |
String : This value cannot be null . |
factory |
SQLiteDatabase.CursorFactory : This value may be null . |
Returns | |
---|---|
SQLiteDatabase |
query
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given URL, returning a Cursor
over the result set.
Parameters | |
---|---|
distinct |
boolean : true if you want each row to be unique, false otherwise. |
table |
String : The table name to compile the query against.
This value cannot be null . |
columns |
String : A list of which columns to return. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used. |
selection |
String : A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table. |
selectionArgs |
String : You may include ?s in selection, which will be
replaced by the values from selectionArgs, in the order that they
appear in the selection. The values will be bound as Strings.
If selection is null or does not contain ?s then selectionArgs
may be null. |
groupBy |
String : A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped. |
having |
String : A filter declare which row groups to include in the cursor,
if row grouping is being used, formatted as an SQL HAVING
clause (excluding the HAVING itself). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used. |
orderBy |
String : How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered. |
limit |
String : Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause. |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
See also:
query
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given table, returning a Cursor
over the result set.
Parameters | |
---|---|
table |
String : The table name to compile the query against.
This value cannot be null . |
columns |
String : A list of which columns to return. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used. |
selection |
String : A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table. |
selectionArgs |
String : You may include ?s in selection, which will be
replaced by the values from selectionArgs, in the order that they
appear in the selection. The values will be bound as Strings.
If selection is null or does not contain ?s then selectionArgs
may be null. |
groupBy |
String : A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped. |
having |
String : A filter declare which row groups to include in the cursor,
if row grouping is being used, formatted as an SQL HAVING
clause (excluding the HAVING itself). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used. |
orderBy |
String : How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered. |
limit |
String : Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause. |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
See also:
query
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
Query the given URL, returning a Cursor
over the result set.
Parameters | |
---|---|
distinct |
boolean : true if you want each row to be unique, false otherwise. |
table |
String : The table name to compile the query against.
This value cannot be null . |
columns |
String : A list of which columns to return. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used. |
selection |
String : A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table. |
selectionArgs |
String : You may include ?s in selection, which will be
replaced by the values from selectionArgs, in the order that they
appear in the selection. The values will be bound as Strings.
If selection is null or does not contain ?s then selectionArgs
may be null. |
groupBy |
String : A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped. |
having |
String : A filter declare which row groups to include in the cursor,
if row grouping is being used, formatted as an SQL HAVING
clause (excluding the HAVING itself). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used. |
orderBy |
String : How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered. |
limit |
String : Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause. |
cancellationSignal |
CancellationSignal : A signal to cancel the operation in progress, or null if none.
If the operation is canceled, then OperationCanceledException will be thrown
when the query is executed. |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
See also:
query
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Query the given table, returning a Cursor
over the result set.
Parameters | |
---|---|
table |
String : The table name to compile the query against.
This value cannot be null . |
columns |
String : A list of which columns to return. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used. |
selection |
String : A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table. |
selectionArgs |
String : You may include ?s in selection, which will be
replaced by the values from selectionArgs, in the order that they
appear in the selection. The values will be bound as Strings.
If selection is null or does not contain ?s then selectionArgs
may be null. |
groupBy |
String : A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped. |
having |
String : A filter declare which row groups to include in the cursor,
if row grouping is being used, formatted as an SQL HAVING
clause (excluding the HAVING itself). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used. |
orderBy |
String : How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered. |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
See also:
queryWithFactory
public Cursor queryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
Query the given URL, returning a Cursor
over the result set.
Parameters | |
---|---|
cursorFactory |
SQLiteDatabase.CursorFactory : the cursor factory to use, or null for the default factory |
distinct |
boolean : true if you want each row to be unique, false otherwise. |
table |
String : The table name to compile the query against.
This value cannot be null . |
columns |
String : A list of which columns to return. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used. |
selection |
String : A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table. |
selectionArgs |
String : You may include ?s in selection, which will be
replaced by the values from selectionArgs, in the order that they
appear in the selection. The values will be bound as Strings.
If selection is null or does not contain ?s then selectionArgs
may be null. |
groupBy |
String : A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped. |
having |
String : A filter declare which row groups to include in the cursor,
if row grouping is being used, formatted as an SQL HAVING
clause (excluding the HAVING itself). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used. |
orderBy |
String : How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered. |
limit |
String : Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause. |
cancellationSignal |
CancellationSignal : A signal to cancel the operation in progress, or null if none.
If the operation is canceled, then OperationCanceledException will be thrown
when the query is executed. |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
See also:
queryWithFactory
public Cursor queryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given URL, returning a Cursor
over the result set.
Parameters | |
---|---|
cursorFactory |
SQLiteDatabase.CursorFactory : the cursor factory to use, or null for the default factory |
distinct |
boolean : true if you want each row to be unique, false otherwise. |
table |
String : The table name to compile the query against.
This value cannot be null . |
columns |
String : A list of which columns to return. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used. |
selection |
String : A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table. |
selectionArgs |
String : You may include ?s in selection, which will be
replaced by the values from selectionArgs, in the order that they
appear in the selection. The values will be bound as Strings.
If selection is null or does not contain ?s then selectionArgs
may be null. |
groupBy |
String : A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped. |
having |
String : A filter declare which row groups to include in the cursor,
if row grouping is being used, formatted as an SQL HAVING
clause (excluding the HAVING itself). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used. |
orderBy |
String : How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered. |
limit |
String : Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause. |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
See also:
rawQuery
public Cursor rawQuery (String sql, String[] selectionArgs, CancellationSignal cancellationSignal)
Runs the provided SQL and returns a Cursor
over the result set.
Parameters | |
---|---|
sql |
String : the SQL query. The SQL string must not be ; terminated
This value cannot be null . |
selectionArgs |
String : You may include ?s in where clause in the query,
which will be replaced by the values from selectionArgs. The
values will be bound as Strings. If selection is null or does not contain ?s then
selectionArgs may be null. |
cancellationSignal |
CancellationSignal : A signal to cancel the operation in progress, or null if none.
If the operation is canceled, then OperationCanceledException will be thrown
when the query is executed. |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
rawQuery
public Cursor rawQuery (String sql, String[] selectionArgs)
Runs the provided SQL and returns a Cursor
over the result set.
Parameters | |
---|---|
sql |
String : the SQL query. The SQL string must not be ; terminated
This value cannot be null . |
selectionArgs |
String : You may include ?s in where clause in the query,
which will be replaced by the values from selectionArgs. The
values will be bound as Strings. If selection is null or does not contain ?s then
selectionArgs may be null. |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
rawQueryWithFactory
public Cursor rawQueryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable, CancellationSignal cancellationSignal)
Runs the provided SQL and returns a cursor over the result set.
Parameters | |
---|---|
cursorFactory |
SQLiteDatabase.CursorFactory : the cursor factory to use, or null for the default factory |
sql |
String : the SQL query. The SQL string must not be ; terminated
This value cannot be null . |
selectionArgs |
String : You may include ?s in where clause in the query,
which will be replaced by the values from selectionArgs. The
values will be bound as Strings. If selection is null or does not contain ?s then
selectionArgs may be null. |
editTable |
String : the name of the first table, which is editable
This value cannot be null . |
cancellationSignal |
CancellationSignal : A signal to cancel the operation in progress, or null if none.
If the operation is canceled, then OperationCanceledException will be thrown
when the query is executed. |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
rawQueryWithFactory
public Cursor rawQueryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable)
Runs the provided SQL and returns a cursor over the result set.
Parameters | |
---|---|
cursorFactory |
SQLiteDatabase.CursorFactory : the cursor factory to use, or null for the default factory |
sql |
String : the SQL query. The SQL string must not be ; terminated
This value cannot be null . |
selectionArgs |
String : You may include ?s in where clause in the query,
which will be replaced by the values from selectionArgs. The
values will be bound as Strings. If selection is null or does not contain ?s then
selectionArgs may be null. |
editTable |
String : the name of the first table, which is editable
This value cannot be null . |
Returns | |
---|---|
Cursor |
A Cursor object, which is positioned before the first entry. Note that
Cursor s are not synchronized, see the documentation for more details.
This value cannot be null . |
releaseMemory
public static int releaseMemory ()
Attempts to release memory that SQLite holds but does not require to operate properly. Typically this memory will come from the page cache.
Returns | |
---|---|
int |
the number of bytes actually released |
replace
public long replace (String table, String nullColumnHack, ContentValues initialValues)
Convenience method for replacing a row in the database. Inserts a new row if a row does not already exist.
Parameters | |
---|---|
table |
String : the table in which to replace the row
This value cannot be null . |
nullColumnHack |
String : optional; may be null .
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided initialValues is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your initialValues is empty. |
initialValues |
ContentValues : this map contains the initial column values for
the row. The keys should be the column names and the values the column values.
This value may be null . |
Returns | |
---|---|
long |
the row ID of the newly inserted row, or -1 if an error occurred |
replaceOrThrow
public long replaceOrThrow (String table, String nullColumnHack, ContentValues initialValues)
Convenience method for replacing a row in the database. Inserts a new row if a row does not already exist.
Parameters | |
---|---|
table |
String : the table in which to replace the row
This value cannot be null . |
nullColumnHack |
String : optional; may be null .
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided initialValues is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your initialValues is empty. |
initialValues |
ContentValues : this map contains the initial column values for
the row. The keys should be the column names and the values the column values.
This value may be null . |
Returns | |
---|---|
long |
the row ID of the newly inserted row, or -1 if an error occurred |
Throws | |
---|---|
|
android.database.SQLException |
SQLException |
setCustomAggregateFunction
public void setCustomAggregateFunction (String functionName, BinaryOperator<String> aggregateFunction)
Register a custom aggregate function that can be called from SQL expressions.
For example, registering a custom aggregation function named
LONGEST
could be used in a query like
SELECT LONGEST(name) FROM employees
.
The implementation of this method follows the reduction flow outlined in
Stream.reduce(BinaryOperator)
, and the custom
aggregation function is expected to be an associative accumulation
function, as defined by that class.
When attempting to register multiple functions with the same function name, SQLite will replace any previously defined functions with the latest definition, regardless of what function type they are. SQLite does not support unregistering functions.
Parameters | |
---|---|
functionName |
String : Case-insensitive name to register this function
under, limited to 255 UTF-8 bytes in length.
This value cannot be null . |
aggregateFunction |
BinaryOperator : Functional interface that will be invoked when
the function name is used by a SQL statement. The argument
values from the SQL statement are passed to the functional
interface, and the return values from the functional interface
are returned back into the SQL statement.
This value cannot be null . |
Throws | |
---|---|
SQLiteException |
if the custom function could not be registered. |
setCustomScalarFunction
public void setCustomScalarFunction (String functionName, UnaryOperator<String> scalarFunction)
Register a custom scalar function that can be called from SQL expressions.
For example, registering a custom scalar function named REVERSE
could be used in a query like
SELECT REVERSE(name) FROM employees
.
When attempting to register multiple functions with the same function name, SQLite will replace any previously defined functions with the latest definition, regardless of what function type they are. SQLite does not support unregistering functions.
Parameters | |
---|---|
functionName |
String : Case-insensitive name to register this function
under, limited to 255 UTF-8 bytes in length.
This value cannot be null . |
scalarFunction |
UnaryOperator : Functional interface that will be invoked when the
function name is used by a SQL statement. The argument values
from the SQL statement are passed to the functional interface,
and the return values from the functional interface are
returned back into the SQL statement.
This value cannot be null . |
Throws | |
---|---|
SQLiteException |
if the custom function could not be registered. |
setForeignKeyConstraintsEnabled
public void setForeignKeyConstraintsEnabled (boolean enable)
Sets whether foreign key constraints are enabled for the database.
By default, foreign key constraints are not enforced by the database. This method allows an application to enable foreign key constraints. It must be called each time the database is opened to ensure that foreign key constraints are enabled for the session.
A good time to call this method is right after calling openOrCreateDatabase(File, CursorFactory)
or in the SQLiteOpenHelper#onConfigure
callback.
When foreign key constraints are disabled, the database does not check whether
changes to the database will violate foreign key constraints. Likewise, when
foreign key constraints are disabled, the database will not execute cascade
delete or update triggers. As a result, it is possible for the database
state to become inconsistent. To perform a database integrity check,
call isDatabaseIntegrityOk()
.
This method must not be called while a transaction is in progress.
See also SQLite Foreign Key Constraints for more details about foreign key constraint support.
Parameters | |
---|---|
enable |
boolean : True to enable foreign key constraints, false to disable them. |
Throws | |
---|---|
IllegalStateException |
if the are transactions is in progress when this method is called. |
setLocale
public void setLocale (Locale locale)
Sets the locale for this database. Does nothing if this database has
the NO_LOCALIZED_COLLATORS
flag set or was opened read only.
Parameters | |
---|---|
locale |
Locale : The new locale. |
Throws | |
---|---|
SQLException |
if the locale could not be set. The most common reason for this is that there is no collator available for the locale you requested. In this case the database remains unchanged. |
setLockingEnabled
public void setLockingEnabled (boolean lockingEnabled)
This method was deprecated
in API level 16.
This method now does nothing. Do not use.
Control whether or not the SQLiteDatabase is made thread-safe by using locks around critical sections. This is pretty expensive, so if you know that your DB will only be used by a single thread then you should set this to false. The default is true.
Parameters | |
---|---|
lockingEnabled |
boolean : set to true to enable locks, false otherwise |
setMaxSqlCacheSize
public void setMaxSqlCacheSize (int cacheSize)
Sets the maximum size of the prepared-statement cache for this database. (size of the cache = number of compiled-sql-statements stored in the cache).
Maximum cache size can ONLY be increased from its current size (default = 10). If this method is called with smaller size than the current maximum value, then IllegalStateException is thrown.
This method is thread-safe.
Parameters | |
---|---|
cacheSize |
int : the size of the cache. can be (0 to MAX_SQL_CACHE_SIZE ) |
Throws | |
---|---|
IllegalStateException |
if input cacheSize > MAX_SQL_CACHE_SIZE . |
setMaximumSize
public long setMaximumSize (long numBytes)
Sets the maximum size the database will grow to. The maximum size cannot be set below the current size.
Parameters | |
---|---|
numBytes |
long : the maximum database size, in bytes |
Returns | |
---|---|
long |
the new maximum database size |
setPageSize
public void setPageSize (long numBytes)
Sets the database page size. The page size must be a power of two. This method does not work if any data has been written to the database file, and must be called right after the database has been created.
Parameters | |
---|---|
numBytes |
long : the database page size, in bytes |
setTransactionSuccessful
public void setTransactionSuccessful ()
Marks the current transaction as successful. Do not do any more database work between calling this and calling endTransaction. Do as little non-database work as possible in that situation too. If any errors are encountered between this and endTransaction the transaction will still be committed.
Throws | |
---|---|
IllegalStateException |
if the current thread is not in a transaction or the transaction is already marked as successful. |
setVersion
public void setVersion (int version)
Sets the database version.
Parameters | |
---|---|
version |
int : the new database version |
toString
public String toString ()
Returns a string representation of the object.
Returns | |
---|---|
String |
a string representation of the object. |
update
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
Convenience method for updating rows in the database.
Parameters | |
---|---|
table |
String : the table to update in
This value cannot be null . |
values |
ContentValues : a map from column names to new column values. null is a
valid value that will be translated to NULL. |
whereClause |
String : the optional WHERE clause to apply when updating.
Passing null will update all rows. |
whereArgs |
String : You may include ?s in the where clause, which
will be replaced by the values from whereArgs. The values
will be bound as Strings. If whereClause is null or does not
contain ?s then whereArgs may be null. |
Returns | |
---|---|
int |
the number of rows affected |
updateWithOnConflict
public int updateWithOnConflict (String table, ContentValues values, String whereClause, String[] whereArgs, int conflictAlgorithm)
Convenience method for updating rows in the database.
Parameters | |
---|---|
table |
String : the table to update in
This value cannot be null . |
values |
ContentValues : a map from column names to new column values. null is a
valid value that will be translated to NULL. |
whereClause |
String : the optional WHERE clause to apply when updating.
Passing null will update all rows. |
whereArgs |
String : You may include ?s in the where clause, which
will be replaced by the values from whereArgs. The values
will be bound as Strings. If whereClause is null or does not
contain ?s then whereArgs may be null. |
conflictAlgorithm |
int : for update conflict resolver |
Returns | |
---|---|
int |
the number of rows affected |
validateSql
public void validateSql (String sql, CancellationSignal cancellationSignal)
Verifies that a SQL SELECT statement is valid by compiling it.
If the SQL statement is not valid, this method will throw a SQLiteException
.
Parameters | |
---|---|
sql |
String : SQL to be validated
This value cannot be null . |
cancellationSignal |
CancellationSignal : A signal to cancel the operation in progress, or null if none.
If the operation is canceled, then OperationCanceledException will be thrown
when the query is executed. |
Throws | |
---|---|
SQLiteException |
if sql is invalid |
yieldIfContended
public boolean yieldIfContended ()
This method was deprecated
in API level 15.
if the db is locked more than once (because of nested transactions) then the lock
will not be yielded. Use yieldIfContendedSafely instead.
Temporarily end the transaction to let other threads run. The transaction is assumed to be successful so far. Do not call setTransactionSuccessful before calling this. When this returns a new transaction will have been created but not marked as successful.
Returns | |
---|---|
boolean |
true if the transaction was yielded |
yieldIfContendedSafely
public boolean yieldIfContendedSafely ()
Temporarily end the transaction to let other threads run. The transaction is assumed to be successful so far. Do not call setTransactionSuccessful before calling this. When this returns a new transaction will have been created but not marked as successful. This assumes that there are no nested transactions (beginTransaction has only been called once) and will throw an exception if that is not the case.
Returns | |
---|---|
boolean |
true if the transaction was yielded |
yieldIfContendedSafely
public boolean yieldIfContendedSafely (long sleepAfterYieldDelay)
Temporarily end the transaction to let other threads run. The transaction is assumed to be successful so far. Do not call setTransactionSuccessful before calling this. When this returns a new transaction will have been created but not marked as successful. This assumes that there are no nested transactions (beginTransaction has only been called once) and will throw an exception if that is not the case.
Parameters | |
---|---|
sleepAfterYieldDelay |
long : if > 0, sleep this long before starting a new transaction if
the lock was actually yielded. This will allow other background threads to make some
more progress than they would if we started the transaction immediately. |
Returns | |
---|---|
boolean |
true if the transaction was yielded |
Protected methods
finalize
protected void finalize ()
Called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.
A subclass overrides the finalize
method to dispose of
system resources or to perform other cleanup.
The general contract of finalize
is that it is invoked
if and when the Java virtual
machine has determined that there is no longer any
means by which this object can be accessed by any thread that has
not yet died, except as a result of an action taken by the
finalization of some other object or class which is ready to be
finalized. The finalize
method may take any action, including
making this object available again to other threads; the usual purpose
of finalize
, however, is to perform cleanup actions before
the object is irrevocably discarded. For example, the finalize method
for an object that represents an input/output connection might perform
explicit I/O transactions to break the connection before the object is
permanently discarded.
The finalize
method of class Object
performs no
special action; it simply returns normally. Subclasses of
Object
may override this definition.
The Java programming language does not guarantee which thread will
invoke the finalize
method for any given object. It is
guaranteed, however, that the thread that invokes finalize will not
be holding any user-visible synchronization locks when finalize is
invoked. If an uncaught exception is thrown by the finalize method,
the exception is ignored and finalization of that object terminates.
After the finalize
method has been invoked for an object, no
further action is taken until the Java virtual machine has again
determined that there is no longer any means by which this object can
be accessed by any thread that has not yet died, including possible
actions by other objects or classes which are ready to be finalized,
at which point the object may be discarded.
The finalize
method is never invoked more than once by a Java
virtual machine for any given object.
Any exception thrown by the finalize
method causes
the finalization of this object to be halted, but is otherwise
ignored.
Throws | |
---|---|
Throwable |
onAllReferencesReleased
protected void onAllReferencesReleased ()
Called when the last reference to the object was released by
a call to releaseReference()
or close()
.
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2024-07-18 UTC.