com.google.firebase.firestore.CollectionReference Java Examples

The following examples show how to use com.google.firebase.firestore.CollectionReference. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void orderAndLimit() {
    CollectionReference citiesRef = db.collection("cities");

    // [START order_and_limit]
    citiesRef.orderBy("name").limit(3);
    // [END order_and_limit]

    // [START order_and_limit_desc]
    citiesRef.orderBy("name", Direction.DESCENDING).limit(3);
    // [END order_and_limit_desc]

    // [START order_by_multiple]
    citiesRef.orderBy("state").orderBy("population", Direction.DESCENDING);
    // [END order_by_multiple]

    // [START filter_and_order]
    citiesRef.whereGreaterThan("population", 100000).orderBy("population").limit(2);
    // [END filter_and_order]

    // [START valid_filter_and_order]
    citiesRef.whereGreaterThan("population", 100000).orderBy("population");
    // [END valid_filter_and_order]
}
 
Example #2
Source File: ConversationManagerTest.java    From NaviBee with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testDeleteFriend() {

    String cid = "conversation";

    // create mocks
    mCollection = mock(CollectionReference.class);
    mDocument = mock(DocumentReference.class);

    // configure mock expected interaction
    when(mFirebaseFirestore.collection("conversations")).thenReturn(mCollection);
    when(mCollection.document(cid)).thenReturn(mDocument);
    when(mDocument.update("isDeleted", true)).thenReturn(null);

    mFirebaseFirestore.collection("conversations").document(cid).update("isDeleted", true);

    // check if mock had expected interaction
    verify(mFirebaseFirestore, times(1)).collection("conversations");
    verify(mCollection, times(1)).document(cid);
    verify(mDocument, times(1)).update("isDeleted", true);

}
 
Example #3
Source File: LeaderboardRepository.java    From triviums with MIT License 6 votes vote down vote up
private void fetchUsers(UserCallback callback){
    CollectionReference collection = firestore.collection("users");

    collection.get().addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            document = task.getResult().getDocuments();
        }
        try {
            callback.onCallback(document);
        } catch (Exception e) {
            if (e instanceof FirebaseFirestoreException) {

            }
            e.printStackTrace();
        }
    })
            .addOnFailureListener(error -> {

            });
}
 
Example #4
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void simpleQueries() {
    // [START simple_queries]
    // Create a reference to the cities collection
    CollectionReference citiesRef = db.collection("cities");

    // Create a query against the collection.
    Query query = citiesRef.whereEqualTo("state", "CA");
    // [END simple_queries]

    // [START simple_query_capital]
    Query capitalCities = db.collection("cities").whereEqualTo("capital", true);
    // [END simple_query_capital]

    // [START example_filters]
    citiesRef.whereEqualTo("state", "CA");
    citiesRef.whereLessThan("population", 100000);
    citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco");
    // [END example_filters]
}
 
Example #5
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
/**
 * Delete all documents in a collection. Uses an Executor to perform work on a background
 * thread. This does *not* automatically discover and delete subcollections.
 */
private Task<Void> deleteCollection(final CollectionReference collection,
                                    final int batchSize,
                                    Executor executor) {

    // Perform the delete operation on the provided Executor, which allows us to use
    // simpler synchronous logic without blocking the main thread.
    return Tasks.call(executor, new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            // Get the first batch of documents in the collection
            Query query = collection.orderBy(FieldPath.documentId()).limit(batchSize);

            // Get a list of deleted documents
            List<DocumentSnapshot> deleted = deleteQueryBatch(query);

            // While the deleted documents in the last batch indicate that there
            // may still be more documents in the collection, page down to the
            // next batch and delete again
            while (deleted.size() >= batchSize) {
                // Move the query cursor to start after the last doc in the batch
                DocumentSnapshot last = deleted.get(deleted.size() - 1);
                query = collection.orderBy(FieldPath.documentId())
                        .startAfter(last.getId())
                        .limit(batchSize);

                deleted = deleteQueryBatch(query);
            }

            return null;
        }
    });

}
 
Example #6
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void orderAndLimitInvalid() {
    CollectionReference citiesRef = db.collection("cities");

    // [START invalid_filter_and_order]
    citiesRef.whereGreaterThan("population", 100000).orderBy("country");
    // [END invalid_filter_and_order]
}
 
Example #7
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void compoundQueriesInvalid() {
    CollectionReference citiesRef = db.collection("cities");

    // [START invalid_range_filters]
    citiesRef.whereGreaterThanOrEqualTo("state", "CA").whereGreaterThan("population", 100000);
    // [END invalid_range_filters]
}
 
Example #8
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void compoundQueries() {
    CollectionReference citiesRef = db.collection("cities");

    // [START chain_filters]
    citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver");
    citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000);
    // [END chain_filters]

    // [START valid_range_filters]
    citiesRef.whereGreaterThanOrEqualTo("state", "CA")
            .whereLessThanOrEqualTo("state", "IN");
    citiesRef.whereEqualTo("state", "CA")
            .whereGreaterThan("population", 1000000);
    // [END valid_range_filters]
}
 
Example #9
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void inQueries() {
    // [START in_filter]
    CollectionReference citiesRef = db.collection("cities");

    citiesRef.whereIn("country", Arrays.asList("USA", "Japan"));
    // [END in_filter]

    // [START in_filter_with_array]
    citiesRef.whereIn("regions", Arrays.asList(new String[]{"west_coast"}, new String[]{"east_coast"}));
    // [END in_filter_with_array]
}
 
Example #10
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void arrayContainsAnyQueries() {
    // [START array_contains_any_filter]
    CollectionReference citiesRef = db.collection("cities");

    citiesRef.whereArrayContainsAny("regions", Arrays.asList("west_coast", "east_coast"));
    // [END array_contains_any_filter]
}
 
Example #11
Source File: ProfileRepository.java    From triviums with MIT License 5 votes vote down vote up
private void fetchProgress(ProgressCallback callback) {
    CollectionReference collectionReference = firestore.collection("users")
            .document(userProfile.getUserUid())
            .collection("categories")
            .document("category")
            .collection("progress");

    collectionReference.get().addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            document = task.getResult().getDocuments();
        }
        callback.onCallback(document);
    });
}
 
Example #12
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void arrayContainsQueries() {
    // [START array_contains_filter]
    CollectionReference citiesRef = db.collection("cities");

    citiesRef.whereArrayContains("regions", "west_coast");
    // [END array_contains_filter]
}
 
Example #13
Source File: FirebaseModule.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
@Singleton
@Provides
@Named("restaurants")
CollectionReference providesRestaurants() {
    FirebaseFirestore.setLoggingEnabled(true);
    return FirebaseFirestore.getInstance().collection("restaurants");
}
 
Example #14
Source File: RestaurantUtil.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
/**
 * Delete all documents in a collection. Uses an Executor to perform work on a background
 * thread. This does *not* automatically discover and delete subcollections.
 */
private static Task<Void> deleteCollection(final CollectionReference collection,
                                           final int batchSize,
                                           Executor executor) {

    // Perform the delete operation on the provided Executor, which allows us to use
    // simpler synchronous logic without blocking the main thread.
    return Tasks.call(executor, () -> {
        // Get the first batch of documents in the collection
        Query query = collection.orderBy("__name__").limit(batchSize);

        // Get a list of deleted documents
        List<DocumentSnapshot> deleted = deleteQueryBatch(query);

        // While the deleted documents in the last batch indicate that there
        // may still be more documents in the collection, page down to the
        // next batch and delete again
        while (deleted.size() >= batchSize) {
            // Move the query cursor to start after the last doc in the batch
            DocumentSnapshot last = deleted.get(deleted.size() - 1);
            query = collection.orderBy("__name__")
                    .startAfter(last.getId())
                    .limit(batchSize);

            deleted = deleteQueryBatch(query);
        }

        return null;
    });

}
 
Example #15
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 4 votes vote down vote up
public void exampleDataCollectionGroup() {
    // [START fs_collection_group_query_data_setup]
    CollectionReference citiesRef = db.collection("cities");

    Map<String, Object> ggbData = new HashMap<>();
    ggbData.put("name", "Golden Gate Bridge");
    ggbData.put("type", "bridge");
    citiesRef.document("SF").collection("landmarks").add(ggbData);

    Map<String, Object> lohData = new HashMap<>();
    lohData.put("name", "Legion of Honor");
    lohData.put("type", "musuem");
    citiesRef.document("SF").collection("landmarks").add(lohData);

    Map<String, Object> gpData = new HashMap<>();
    gpData.put("name", "Griffith Park");
    gpData.put("type", "park");
    citiesRef.document("LA").collection("landmarks").add(gpData);

    Map<String, Object> tgData = new HashMap<>();
    tgData.put("name", "The Getty");
    tgData.put("type", "museum");
    citiesRef.document("LA").collection("landmarks").add(tgData);

    Map<String, Object> lmData = new HashMap<>();
    lmData.put("name", "Lincoln Memorial");
    lmData.put("type", "memorial");
    citiesRef.document("DC").collection("landmarks").add(lmData);

    Map<String, Object> nasaData = new HashMap<>();
    nasaData.put("name", "National Air and Space Musuem");
    nasaData.put("type", "museum");
    citiesRef.document("DC").collection("landmarks").add(nasaData);

    Map<String, Object> upData = new HashMap<>();
    upData.put("name", "Ueno Park");
    upData.put("type", "park");
    citiesRef.document("TOK").collection("landmarks").add(upData);

    Map<String, Object> nmData = new HashMap<>();
    nmData.put("name", "National Musuem of Nature and Science");
    nmData.put("type", "museum");
    citiesRef.document("TOK").collection("landmarks").add(nmData);

    Map<String, Object> jpData = new HashMap<>();
    jpData.put("name", "Jingshan Park");
    jpData.put("type", "park");
    citiesRef.document("BJ").collection("landmarks").add(jpData);

    Map<String, Object> baoData = new HashMap<>();
    baoData.put("name", "Beijing Ancient Observatory");
    baoData.put("type", "museum");
    citiesRef.document("BJ").collection("landmarks").add(baoData);
    // [END fs_collection_group_query_data_setup]
}
 
Example #16
Source File: FirestoreArrayTest.java    From FirebaseUI-Android with Apache License 2.0 4 votes vote down vote up
private String getConsoleLink(CollectionReference reference) {
    String base = "https://console.firebase.google.com/project/firebaseuitests/database/firestore/data/";
    return base + reference.getPath();
}
 
Example #17
Source File: IntegrationTestUtil.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public static CollectionReference testCollection() {
  return testFirestore().collection(autoId());
}
 
Example #18
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 4 votes vote down vote up
public void exampleData() {
    // [START example_data]
    CollectionReference cities = db.collection("cities");

    Map<String, Object> data1 = new HashMap<>();
    data1.put("name", "San Francisco");
    data1.put("state", "CA");
    data1.put("country", "USA");
    data1.put("capital", false);
    data1.put("population", 860000);
    data1.put("regions", Arrays.asList("west_coast", "norcal"));
    cities.document("SF").set(data1);

    Map<String, Object> data2 = new HashMap<>();
    data2.put("name", "Los Angeles");
    data2.put("state", "CA");
    data2.put("country", "USA");
    data2.put("capital", false);
    data2.put("population", 3900000);
    data2.put("regions", Arrays.asList("west_coast", "socal"));
    cities.document("LA").set(data2);

    Map<String, Object> data3 = new HashMap<>();
    data3.put("name", "Washington D.C.");
    data3.put("state", null);
    data3.put("country", "USA");
    data3.put("capital", true);
    data3.put("population", 680000);
    data3.put("regions", Arrays.asList("east_coast"));
    cities.document("DC").set(data3);

    Map<String, Object> data4 = new HashMap<>();
    data4.put("name", "Tokyo");
    data4.put("state", null);
    data4.put("country", "Japan");
    data4.put("capital", true);
    data4.put("population", 9000000);
    data4.put("regions", Arrays.asList("kanto", "honshu"));
    cities.document("TOK").set(data4);

    Map<String, Object> data5 = new HashMap<>();
    data5.put("name", "Beijing");
    data5.put("state", null);
    data5.put("country", "China");
    data5.put("capital", true);
    data5.put("population", 21500000);
    data5.put("regions", Arrays.asList("jingjinji", "hebei"));
    cities.document("BJ").set(data5);
    // [END example_data]
}
 
Example #19
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 4 votes vote down vote up
public void collectionReference() {
    // [START collection_reference]
    CollectionReference usersCollectionRef = db.collection("users");
    // [END collection_reference]
}
 
Example #20
Source File: RestaurantUtil.java    From firestore-android-arch-components with Apache License 2.0 4 votes vote down vote up
/**
 * Delete all restaurants.
 */
public static Task<Void> deleteAll(final CollectionReference ref) {
    return deleteCollection(ref, 25, EXECUTOR);
}
 
Example #21
Source File: RestaurantRepository.java    From firestore-android-arch-components with Apache License 2.0 4 votes vote down vote up
@Inject
public RestaurantRepository(@Named("restaurants") CollectionReference restaurants) {
    this.restaurants = restaurants;
}
 
Example #22
Source File: FeaturesCollectionReference.java    From ground-android with Apache License 2.0 4 votes vote down vote up
FeaturesCollectionReference(CollectionReference ref) {
  super(ref);
}
 
Example #23
Source File: RecordsCollectionReference.java    From ground-android with Apache License 2.0 4 votes vote down vote up
RecordsCollectionReference(CollectionReference ref) {
  super(ref);
}
 
Example #24
Source File: ProjectsCollectionReference.java    From ground-android with Apache License 2.0 4 votes vote down vote up
ProjectsCollectionReference(CollectionReference ref) {
  super(ref);
}
 
Example #25
Source File: FluentCollectionReference.java    From ground-android with Apache License 2.0 4 votes vote down vote up
protected CollectionReference reference() {
  return reference;
}
 
Example #26
Source File: FluentCollectionReference.java    From ground-android with Apache License 2.0 4 votes vote down vote up
protected FluentCollectionReference(CollectionReference reference) {
  this.reference = reference;
}
 
Example #27
Source File: IntegrationTestUtil.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public static void writeAllDocs(
    CollectionReference collection, Map<String, Map<String, Object>> docs) {
  for (Map.Entry<String, Map<String, Object>> doc : docs.entrySet()) {
    waitFor(collection.document(doc.getKey()).set(doc.getValue()));
  }
}
 
Example #28
Source File: IntegrationTestUtil.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public static CollectionReference testCollectionWithDocs(Map<String, Map<String, Object>> docs) {
  CollectionReference collection = testCollection();
  CollectionReference writer = testFirestore().collection(collection.getId());
  writeAllDocs(writer, docs);
  return collection;
}
 
Example #29
Source File: IntegrationTestUtil.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public static CollectionReference testCollection(String name) {
  return testFirestore().collection(name + "_" + autoId());
}