FirebaseFirestore
public class FirebaseFirestore
Represents a Cloud Firestore database and is the entry point for all Cloud Firestore operations.
Subclassing Note: Cloud Firestore classes are not meant to be subclassed except for use in test mocks. Subclassing is not supported in production code and new SDK releases may break code that does so.
Summary
Public fields |
|
|---|---|
@Nullable PersistentCacheIndexManager |
Public methods |
|
|---|---|
@NonNull ListenerRegistration |
addSnapshotsInSyncListener(@NonNull Runnable runnable)Attaches a listener for a snapshots-in-sync event. |
@NonNull ListenerRegistration |
addSnapshotsInSyncListener(Attaches a listener for a snapshots-in-sync event. |
@NonNull ListenerRegistration |
addSnapshotsInSyncListener(Attaches a listener for a snapshots-in-sync event. |
@NonNull WriteBatch |
batch()Creates a write batch, used for performing multiple writes as a single atomic operation. |
@NonNull Task<Void> |
Clears the persistent storage, including pending writes and cached documents. |
@NonNull CollectionReference |
collection(@NonNull String collectionPath)Gets a |
@NonNull Query |
collectionGroup(@NonNull String collectionId)Creates and returns a new |
@NonNull Task<Void> |
Disables network access for this instance. |
@NonNull DocumentReference |
Gets a `DocumentReference` instance that refers to the document at the specified path within the database. |
@NonNull Task<Void> |
Re-enables network usage for this instance after a prior call to |
@NonNull FirebaseApp |
getApp()Returns the FirebaseApp instance to which this |
@NonNull FirebaseFirestoreSettings |
Returns the settings used by this |
static @NonNull FirebaseFirestore |
Returns the default |
static @NonNull FirebaseFirestore |
getInstance(@NonNull FirebaseApp app)Returns the default |
static @NonNull FirebaseFirestore |
getInstance(@NonNull String database)Returns the |
static @NonNull FirebaseFirestore |
getInstance(@NonNull FirebaseApp app, @NonNull String database)Returns the |
@NonNull Task<Query> |
getNamedQuery(@NonNull String name)Reads a Firestore |
@Nullable PersistentCacheIndexManager |
Gets the |
@NonNull LoadBundleTask |
loadBundle(@NonNull byte[] bundleData)Loads a Firestore bundle into the local cache. |
@NonNull LoadBundleTask |
loadBundle(@NonNull ByteBuffer bundleData)Loads a Firestore bundle into the local cache. |
@NonNull LoadBundleTask |
loadBundle(@NonNull InputStream bundleData)Loads a Firestore bundle into the local cache. |
@NonNull Task<Void> |
runBatch(@NonNull WriteBatch.Function batchFunction)Executes a batchFunction on a newly created |
@NonNull Task<TResult> |
<TResult> runTransaction(Executes the given |
@NonNull Task<TResult> |
<TResult> runTransaction(Executes the given |
void |
setFirestoreSettings(@NonNull FirebaseFirestoreSettings settings)Sets any custom settings used to configure this |
@NonNull Task<Void> |
This method is deprecated. Instead of creating cache indexes manually, consider using |
static void |
setLoggingEnabled(boolean loggingEnabled)Globally enables / disables Cloud Firestore logging for the SDK. |
@NonNull Task<Void> |
Terminates this |
void |
useEmulator(@NonNull String host, int port)Modifies this FirebaseDatabase instance to communicate with the Cloud Firestore emulator. |
@NonNull Task<Void> |
Waits until all currently pending writes for the active user have been acknowledged by the backend. |
Public fields
persistentCacheIndexManager
public @Nullable PersistentCacheIndexManager persistentCacheIndexManager
Public methods
addSnapshotsInSyncListener
public @NonNull ListenerRegistration addSnapshotsInSyncListener(@NonNull Runnable runnable)
Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event indicates that all listeners affected by a given change have fired, even if a single server-generated change affects multiple listeners.
NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, but does not relate to whether those snapshots are in sync with the server. Use SnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or the server.
| Parameters | |
|---|---|
@NonNull Runnable runnable |
A callback to be called every time all snapshot listeners are in sync with each other. |
| Returns | |
|---|---|
@NonNull ListenerRegistration |
A registration object that can be used to remove the listener. |
addSnapshotsInSyncListener
public @NonNull ListenerRegistration addSnapshotsInSyncListener(
@NonNull Activity activity,
@NonNull Runnable runnable
)
Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event indicates that all listeners affected by a given change have fired, even if a single server-generated change affects multiple listeners.
NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, but does not relate to whether those snapshots are in sync with the server. Use SnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or the server.
| Parameters | |
|---|---|
@NonNull Activity activity |
The activity to scope the listener to. |
@NonNull Runnable runnable |
A callback to be called every time all snapshot listeners are in sync with each other. |
| Returns | |
|---|---|
@NonNull ListenerRegistration |
A registration object that can be used to remove the listener. |
addSnapshotsInSyncListener
public @NonNull ListenerRegistration addSnapshotsInSyncListener(
@NonNull Executor executor,
@NonNull Runnable runnable
)
Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event indicates that all listeners affected by a given change have fired, even if a single server-generated change affects multiple listeners.
NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, but does not relate to whether those snapshots are in sync with the server. Use SnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or the server.
| Parameters | |
|---|---|
@NonNull Executor executor |
The executor to use to call the listener. |
@NonNull Runnable runnable |
A callback to be called every time all snapshot listeners are in sync with each other. |
| Returns | |
|---|---|
@NonNull ListenerRegistration |
A registration object that can be used to remove the listener. |
batch
public @NonNull WriteBatch batch()
Creates a write batch, used for performing multiple writes as a single atomic operation.
The maximum number of writes allowed in a single batch is 500, but note that each usage of serverTimestamp, arrayUnion, arrayRemove, or increment inside a transaction counts as an additional write.
| Returns | |
|---|---|
@NonNull WriteBatch |
The created WriteBatch object. |
clearPersistence
public @NonNull Task<Void> clearPersistence()
Clears the persistent storage, including pending writes and cached documents.
Must be called while the FirebaseFirestore instance is not started (after the app is shutdown or when the app is first initialized). On startup, this method must be called before other methods (other than setFirestoreSettings). If the FirebaseFirestore instance is still running, the Task will fail with an error code of FAILED_PRECONDITION.
Note: clearPersistence() is primarily intended to help write reliable tests that use Cloud Firestore. It uses an efficient mechanism for dropping existing data but does not attempt to securely overwrite or otherwise make cached data unrecoverable. For applications that are sensitive to the disclosure of cached data in between user sessions, we strongly recommend not enabling persistence at all.
collection
public @NonNull CollectionReference collection(@NonNull String collectionPath)
Gets a CollectionReference instance that refers to the collection at the specified path within the database.
| Returns | |
|---|---|
@NonNull CollectionReference |
The |
collectionGroup
public @NonNull Query collectionGroup(@NonNull String collectionId)
Creates and returns a new Query that includes all documents in the database that are contained in a collection or subcollection with the given collectionId.
disableNetwork
public @NonNull Task<Void> disableNetwork()
Disables network access for this instance. While the network is disabled, any snapshot listeners or get() calls will return results from cache, and any write operations will be queued until network usage is re-enabled via a call to enableNetwork.
document
public @NonNull DocumentReference document(@NonNull String documentPath)
Gets a `DocumentReference` instance that refers to the document at the specified path within the database.
| Returns | |
|---|---|
@NonNull DocumentReference |
The DocumentReference instance. |
enableNetwork
public @NonNull Task<Void> enableNetwork()
Re-enables network usage for this instance after a prior call to disableNetwork.
getApp
public @NonNull FirebaseApp getApp()
Returns the FirebaseApp instance to which this FirebaseFirestore belongs.
getFirestoreSettings
public @NonNull FirebaseFirestoreSettings getFirestoreSettings()
Returns the settings used by this FirebaseFirestore object.
getInstance
public static @NonNull FirebaseFirestore getInstance()
Returns the default FirebaseFirestore instance for the default FirebaseApp.
Returns the same instance for all invocations. If no instance exists, initializes a new instance.
The FirebaseFirestore instance.
getInstance
public static @NonNull FirebaseFirestore getInstance(@NonNull FirebaseApp app)
Returns the default FirebaseFirestore instance for the provided FirebaseApp.
For a given FirebaseApp, invocation always returns the same instance. If no instance exists, initializes a new instance.
The FirebaseFirestore instance.
| Parameters | |
|---|---|
@NonNull FirebaseApp app |
The |
getInstance
public static @NonNull FirebaseFirestore getInstance(@NonNull String database)
Returns the FirebaseFirestore instance for the default FirebaseApp.
Returns the same instance for all invocations given the same database parameter. If no instance exists, initializes a new instance.
The FirebaseFirestore instance.
getInstance
public static @NonNull FirebaseFirestore getInstance(@NonNull FirebaseApp app, @NonNull String database)
Returns the FirebaseFirestore instance for the provided FirebaseApp.
Returns the same instance for all invocations given the same FirebaseApp and database parameter. If no instance exists, initializes a new instance.
The FirebaseFirestore instance.
| Parameters | |
|---|---|
@NonNull FirebaseApp app |
The |
@NonNull String database |
The database ID. |
getNamedQuery
public @NonNull Task<Query> getNamedQuery(@NonNull String name)
Reads a Firestore Query from local cache, identified by the given name.
The named queries are packaged into bundles on the server side (along with resulting documents) and loaded to local cache using loadBundle. Once in local cache, you can use this method to extract a query by name.
getPersistentCacheIndexManager
public @Nullable PersistentCacheIndexManager getPersistentCacheIndexManager()
Gets the PersistentCacheIndexManager instance used by this FirebaseFirestore object.
This is not the same as Cloud Firestore Indexes. Persistent cache indexes are optional indexes that only exist within the SDK to assist in local query execution.
| Returns | |
|---|---|
@Nullable PersistentCacheIndexManager |
The |
loadBundle
public @NonNull LoadBundleTask loadBundle(@NonNull byte[] bundleData)
Loads a Firestore bundle into the local cache.
| Parameters | |
|---|---|
@NonNull byte[] bundleData |
A byte array representing the bundle to be loaded. |
| Returns | |
|---|---|
@NonNull LoadBundleTask |
A |
loadBundle
public @NonNull LoadBundleTask loadBundle(@NonNull ByteBuffer bundleData)
Loads a Firestore bundle into the local cache.
| Parameters | |
|---|---|
@NonNull ByteBuffer bundleData |
A ByteBuffer representing the bundle to be loaded. |
| Returns | |
|---|---|
@NonNull LoadBundleTask |
A |
loadBundle
public @NonNull LoadBundleTask loadBundle(@NonNull InputStream bundleData)
Loads a Firestore bundle into the local cache.
| Parameters | |
|---|---|
@NonNull InputStream bundleData |
A stream representing the bundle to be loaded. |
| Returns | |
|---|---|
@NonNull LoadBundleTask |
A |
runBatch
public @NonNull Task<Void> runBatch(@NonNull WriteBatch.Function batchFunction)
Executes a batchFunction on a newly created WriteBatch and then commits all of the writes made by the batchFunction as a single atomic unit.
| Parameters | |
|---|---|
@NonNull WriteBatch.Function batchFunction |
The function to execute within the batch context. |
runTransaction
public @NonNull Task<TResult> <TResult> runTransaction(
@NonNull Transaction.Function<TResult> updateFunction
)
Executes the given updateFunction and then attempts to commit the changes applied within the transaction. If any document read within the transaction has changed, the updateFunction will be retried. If it fails to commit after 5 attempts (the default failure limit), the transaction will fail. To have a different number of retries, use the runTransaction method instead.
| Parameters | |
|---|---|
@NonNull Transaction.Function<TResult> updateFunction |
The function to execute within the transaction context. |
runTransaction
public @NonNull Task<TResult> <TResult> runTransaction(
@NonNull TransactionOptions options,
@NonNull Transaction.Function<TResult> updateFunction
)
Executes the given updateFunction and then attempts to commit the changes applied within the transaction. If any document read within the transaction has changed, the updateFunction will be retried. If it fails to commit after the maxmimum number of attempts specified in transactionOptions, the transaction will fail.
| Parameters | |
|---|---|
@NonNull TransactionOptions options |
The transaction options for controlling execution. |
@NonNull Transaction.Function<TResult> updateFunction |
The function to execute within the transaction context. |
setFirestoreSettings
public void setFirestoreSettings(@NonNull FirebaseFirestoreSettings settings)
Sets any custom settings used to configure this FirebaseFirestore object. This method can only be called before calling any other methods on this object.
setIndexConfiguration
@PreviewApi
public @NonNull Task<Void>setIndexConfiguration(@NonNull String json)
Configures indexing for local query execution. Any previous index configuration is overridden. The Task resolves once the index configuration has been persisted.
The index entries themselves are created asynchronously. You can continue to use queries that require indexing even if the indices are not yet available. Query execution will automatically start using the index once the index entries have been written.
The method accepts the JSON format exported by the Firebase CLI (`firebase firestore:indexes`). If the JSON format is invalid, this method throws an exception.
| Throws | |
|---|---|
java.lang.IllegalArgumentException java.lang.IllegalArgumentException |
if the JSON format is invalid |
setLoggingEnabled
public static void setLoggingEnabled(boolean loggingEnabled)
Globally enables / disables Cloud Firestore logging for the SDK.
terminate
public @NonNull Task<Void> terminate()
Terminates this FirebaseFirestore instance.
After calling terminate() only the clearPersistence method may be used. Any other method will throw an IllegalStateException.
To restart after termination, simply create a new instance of FirebaseFirestore with getInstance or getInstance.
terminate() does not cancel any pending writes and any tasks that are awaiting a response from the server will not be resolved. The next time you start this instance, it will resume attempting to send these writes to the server.
Note: Under normal circumstances, calling terminate() is not required. This method is useful only when you want to force this instance to release all of its resources or in combination with clearPersistence to ensure that all local state is destroyed between test runs.
useEmulator
public void useEmulator(@NonNull String host, int port)
Modifies this FirebaseDatabase instance to communicate with the Cloud Firestore emulator.
Note: Call this method before using the instance to do any database operations.
waitForPendingWrites
public @NonNull Task<Void> waitForPendingWrites()
Waits until all currently pending writes for the active user have been acknowledged by the backend.
The returned Task completes immediately if there are no outstanding writes. Otherwise, the Task waits for all previously issued writes (including those written in a previous app session), but it does not wait for writes that were added after the method is called. If you wish to wait for additional writes, you have to call waitForPendingWrites() again.
Any outstanding waitForPendingWrites() Tasks are cancelled during user changes.