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 methods

@NonNull ListenerRegistration

Attaches a listener for a snapshots-in-sync event.

@NonNull ListenerRegistration
addSnapshotsInSyncListener(
    @NonNull Activity activity,
    @NonNull Runnable runnable
)

Attaches a listener for a snapshots-in-sync event.

@NonNull ListenerRegistration
addSnapshotsInSyncListener(
    @NonNull Executor executor,
    @NonNull Runnable runnable
)

Attaches a listener for a snapshots-in-sync event.

@NonNull WriteBatch

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 CollectionReference instance that refers to the collection at the specified path within the database.

@NonNull Query

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.

@NonNull Task<Void>

Disables network access for this instance.

@NonNull DocumentReference
document(@NonNull String documentPath)

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 disableNetwork.

@NonNull FirebaseApp

Returns the FirebaseApp instance to which this FirebaseFirestore belongs.

@NonNull FirebaseFirestoreSettings

Returns the settings used by this FirebaseFirestore object.

static @NonNull FirebaseFirestore

Returns the default FirebaseFirestore instance for the default FirebaseApp.

static @NonNull FirebaseFirestore

Returns the default FirebaseFirestore instance for the provided FirebaseApp.

static @NonNull FirebaseFirestore

Returns the FirebaseFirestore instance for the default FirebaseApp.

static @NonNull FirebaseFirestore

Returns the FirebaseFirestore instance for the provided FirebaseApp.

@NonNull Task<Query>

Reads a Firestore Query from local cache, identified by the given name.

@Nullable PersistentCacheIndexManager

Gets the PersistentCacheIndexManager instance used by this FirebaseFirestore object.

@NonNull LoadBundleTask
loadBundle(@NonNull byte[] bundleData)

Loads a Firestore bundle into the local cache.

@NonNull LoadBundleTask

Loads a Firestore bundle into the local cache.

@NonNull LoadBundleTask

Loads a Firestore bundle into the local cache.

@NonNull Task<Void>

Executes a batchFunction on a newly created WriteBatch and then commits all of the writes made by the batchFunction as a single atomic unit.

@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.

@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.

void

Sets any custom settings used to configure this FirebaseFirestore object.

@NonNull Task<Void>

This method is deprecated.

Instead of creating cache indexes manually, consider using enableIndexAutoCreation to let the SDK decide whether to create cache indexes for queries running locally.

static void
setLoggingEnabled(boolean loggingEnabled)

Globally enables / disables Cloud Firestore logging for the SDK.

@NonNull Task<Void>

Terminates this FirebaseFirestore instance.

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<VoidclearPersistence()

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.

Returns
@NonNull Task<Void>

A Task that is resolved when the persistent storage is cleared. Otherwise, the Task is rejected with an error.

collection

public @NonNull CollectionReference collection(@NonNull String collectionPath)

Gets a CollectionReference instance that refers to the collection at the specified path within the database.

Parameters
@NonNull String collectionPath

A slash-separated path to a collection.

Returns
@NonNull CollectionReference

The CollectionReference instance.

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.

Parameters
@NonNull String collectionId

Identifies the collections to query over. Every collection or subcollection with this ID as the last segment of its path will be included. Cannot contain a slash.

Returns
@NonNull Query

The created Query.

disableNetwork

public @NonNull Task<VoiddisableNetwork()

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.

Returns
@NonNull Task<Void>

A Task that will be completed once networking is disabled.

document

public @NonNull DocumentReference document(@NonNull String documentPath)

Gets a `DocumentReference` instance that refers to the document at the specified path within the database.

Parameters
@NonNull String documentPath

A slash-separated path to a document.

Returns
@NonNull DocumentReference

The DocumentReference instance.

enableNetwork

public @NonNull Task<VoidenableNetwork()

Re-enables network usage for this instance after a prior call to disableNetwork.

Returns
@NonNull Task<Void>

A Task that will be completed once networking is enabled.

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 FirebaseApp instance that the returned FirebaseFirestore instance is associated with.

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.

Parameters
@NonNull String database

The database ID.

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 FirebaseApp instance that the returned FirebaseFirestore instance is associated with.

@NonNull String database

The database ID.

getNamedQuery

public @NonNull Task<QuerygetNamedQuery(@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 PersistentCacheIndexManager instance or null if local persistent storage is not in use.

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 LoadBundleTask, which notifies callers with progress updates, and completion or error events.

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 LoadBundleTask, which notifies callers with progress updates, and completion or error events.

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 LoadBundleTask, which notifies callers with progress updates, and completion or error events.

runBatch

public @NonNull Task<VoidrunBatch(@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.

Returns
@NonNull Task<Void>

A Task that will be resolved when the batch has been committed.

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.

Returns
@NonNull Task<TResult>

The task returned from the updateFunction.

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.

Returns
@NonNull Task<TResult>

The task returned from the updateFunction.

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<VoidsetIndexConfiguration(@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.

Parameters
@NonNull String json

The JSON format exported by the Firebase CLI.

Returns
@NonNull Task<Void>

A task that resolves once all indices are successfully configured.

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<Voidterminate()

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.

Returns
@NonNull Task<Void>

A Task that is resolved when the instance has been successfully terminated.

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.

Parameters
@NonNull String host

the emulator host (for example, 10.0.2.2)

int port

the emulator port (for example, 8080)

waitForPendingWrites

public @NonNull Task<VoidwaitForPendingWrites()

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.

Returns
@NonNull Task<Void>

A Task which resolves when all currently pending writes have been acknowledged by the backend.