com.google.firebase.firestore.Query Java Examples

The following examples show how to use com.google.firebase.firestore.Query. 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: PageKey.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@NonNull
public Query getPageQuery(@NonNull Query baseQuery, int size) {
    Query pageQuery = baseQuery;

    if (mStartAfter != null) {
        pageQuery = pageQuery.startAfter(mStartAfter);
    }

    if (mEndBefore != null) {
        pageQuery = pageQuery.endBefore(mEndBefore);
    } else {
        pageQuery = pageQuery.limit(size);
    }

    return pageQuery;
}
 
Example #2
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void detachListener() {
    // [START detach_listener]
    Query query = db.collection("cities");
    ListenerRegistration registration = query.addSnapshotListener(
            new EventListener<QuerySnapshot>() {
                // [START_EXCLUDE]
                @Override
                public void onEvent(@Nullable QuerySnapshot snapshots,
                                    @Nullable FirebaseFirestoreException e) {
                    // ...
                }
                // [END_EXCLUDE]
            });

    // ...

    // Stop listening to changes
    registration.remove();
    // [END detach_listener]
}
 
Example #3
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 #4
Source File: FilterDialogFragment.java    From friendlyeats-android with Apache License 2.0 5 votes vote down vote up
@Nullable
private Query.Direction getSortDirection() {
    String selected = (String) mSortSpinner.getSelectedItem();
    if (getString(R.string.sort_by_rating).equals(selected)) {
        return Query.Direction.DESCENDING;
    } if (getString(R.string.sort_by_price).equals(selected)) {
        return Query.Direction.ASCENDING;
    } if (getString(R.string.sort_by_popularity).equals(selected)) {
        return Query.Direction.DESCENDING;
    }

    return null;
}
 
Example #5
Source File: FilterDialogFragment.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
@Nullable
private Query.Direction getSortDirection() {
    String selected = (String) binding.spinnerSort.getSelectedItem();
    if (getString(R.string.sort_by_rating).equals(selected)) {
        return Query.Direction.DESCENDING;
    }
    if (getString(R.string.sort_by_price).equals(selected)) {
        return Query.Direction.ASCENDING;
    }
    if (getString(R.string.sort_by_popularity).equals(selected)) {
        return Query.Direction.DESCENDING;
    }

    return null;
}
 
Example #6
Source File: Filters.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
public static Filters getDefault() {
    Filters filters = new Filters();
    filters.setSortBy(Restaurant.FIELD_AVG_RATING);
    filters.setSortDirection(Query.Direction.DESCENDING);

    return filters;
}
 
Example #7
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 #8
Source File: MainRepository.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
private Query toQuery(final Filters filters) {
    // Construct query basic query
    Query query = firestore.collection("restaurants");

    if (filters == null) {
        query.orderBy("avgRating", Query.Direction.ASCENDING);
    } else {
        // Category (equality filter)
        if (filters.hasCategory()) {
            query = query.whereEqualTo(Restaurant.FIELD_CATEGORY, filters.getCategory());
        }

        // City (equality filter)
        if (filters.hasCity()) {
            query = query.whereEqualTo(Restaurant.FIELD_CITY, filters.getCity());
        }

        // Price (equality filter)
        if (filters.hasPrice()) {
            query = query.whereEqualTo(Restaurant.FIELD_PRICE, filters.getPrice());
        }

        // Sort by (orderBy with direction)
        if (filters.hasSortBy()) {
            query = query.orderBy(filters.getSortBy(), filters.getSortDirection());
        }
    }

    /* query could be limited like: query.limit(5) */
    return query;
}
 
Example #9
Source File: MainActivity.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onFilter(Filters filters) {
    // Construct query basic query
    Query query = mFirestore.collection("restaurants");

    // Category (equality filter)
    if (filters.hasCategory()) {
        query = query.whereEqualTo(Restaurant.FIELD_CATEGORY, filters.getCategory());
    }

    // City (equality filter)
    if (filters.hasCity()) {
        query = query.whereEqualTo(Restaurant.FIELD_CITY, filters.getCity());
    }

    // Price (equality filter)
    if (filters.hasPrice()) {
        query = query.whereEqualTo(Restaurant.FIELD_PRICE, filters.getPrice());
    }

    // Sort by (orderBy with direction)
    if (filters.hasSortBy()) {
        query = query.orderBy(filters.getSortBy(), filters.getSortDirection());
    }

    // Limit items
    query = query.limit(LIMIT);

    // Update the query
    mAdapter.setQuery(query);

    // Set header
    mBinding.textCurrentSearch.setText(HtmlCompat.fromHtml(filters.getSearchDescription(this),
            HtmlCompat.FROM_HTML_MODE_LEGACY));
    mBinding.textCurrentSortBy.setText(filters.getOrderDescription(this));

    // Save filters
    mViewModel.setFilters(filters);
}
 
Example #10
Source File: RestaurantUtil.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
/**
 * Delete all results from a query in a single WriteBatch. Must be run on a worker thread
 * to avoid blocking/crashing the main thread.
 */
@WorkerThread
private static List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());

    WriteBatch batch = query.getFirestore().batch();
    for (DocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());

    return querySnapshot.getDocuments();
}
 
Example #11
Source File: Filters.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
public static Filters getDefault() {
    Filters filters = new Filters();
    filters.setSortBy(Restaurant.FIELD_AVG_RATING);
    filters.setSortDirection(Query.Direction.DESCENDING);

    return filters;
}
 
Example #12
Source File: FirestoreAdapter.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
public void setQuery(Query query) {
    // Stop listening
    stopListening();

    // Clear existing data
    mSnapshots.clear();
    notifyDataSetChanged();

    // Listen to new query
    mQuery = query;
    startListening();
}
 
Example #13
Source File: Filters.java    From friendlyeats-android with Apache License 2.0 5 votes vote down vote up
public static Filters getDefault() {
    Filters filters = new Filters();
    filters.setSortBy(Restaurant.FIELD_AVG_RATING);
    filters.setSortDirection(Query.Direction.DESCENDING);

    return filters;
}
 
Example #14
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
/**
 * Delete all results from a query in a single WriteBatch. Must be run on a worker thread
 * to avoid blocking/crashing the main thread.
 */
@WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());

    WriteBatch batch = query.getFirestore().batch();
    for (QueryDocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());

    return querySnapshot.getDocuments();
}
 
Example #15
Source File: FilterDialogFragment.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
@Nullable
private Query.Direction getSortDirection() {
    String selected = (String) mBinding.spinnerSort.getSelectedItem();
    if (getString(R.string.sort_by_rating).equals(selected)) {
        return Query.Direction.DESCENDING;
    } if (getString(R.string.sort_by_price).equals(selected)) {
        return Query.Direction.ASCENDING;
    } if (getString(R.string.sort_by_popularity).equals(selected)) {
        return Query.Direction.DESCENDING;
    }

    return null;
}
 
Example #16
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 #17
Source File: FirestoreArray.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * @param changes metadata options for the query listen.
 * @see #FirestoreArray(Query, SnapshotParser)
 */
public FirestoreArray(@NonNull Query query,
                      @NonNull MetadataChanges changes,
                      @NonNull SnapshotParser<T> parser) {
    super(parser);
    mQuery = query;
    mMetadataChanges = changes;
}
 
Example #18
Source File: FirestoreRecyclerOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Set the query to use (with options) and provide a model class to which each snapshot will
 * be converted.
 * <p>
 * Do not call this method after calling {@link #setSnapshotArray(ObservableSnapshotArray)}.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull MetadataChanges changes,
                           @NonNull Class<T> modelClass) {
    return setQuery(query, changes, new ClassSnapshotParser<>(modelClass));
}
 
Example #19
Source File: FirestoreRecyclerOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Set the query to use (with options) and provide a custom {@link SnapshotParser}.
 * <p>
 * Do not call this method after calling {@link #setSnapshotArray(ObservableSnapshotArray)}.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull MetadataChanges changes,
                           @NonNull SnapshotParser<T> parser) {
    assertNull(mSnapshots, ERR_SNAPSHOTS_SET);

    mSnapshots = new FirestoreArray<>(query, changes, parser);
    return this;
}
 
Example #20
Source File: FirestoreAdapter.java    From friendlyeats-android with Apache License 2.0 5 votes vote down vote up
public void setQuery(Query query) {
    // Stop listening
    stopListening();

    // Clear existing data
    mSnapshots.clear();
    notifyDataSetChanged();

    // Listen to new query
    mQuery = query;
    startListening();
}
 
Example #21
Source File: FirestorePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the query using {@link Source#DEFAULT} and a {@link ClassSnapshotParser} based
 * on the given Class.
 *
 * See {@link #setQuery(Query, Source, PagedList.Config, SnapshotParser)}.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull PagedList.Config config,
                           @NonNull Class<T> modelClass) {
    return setQuery(query, Source.DEFAULT, config, modelClass);
}
 
Example #22
Source File: FirestorePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the query using {@link Source#DEFAULT} and a custom {@link SnapshotParser}.
 *
 * See {@link #setQuery(Query, Source, PagedList.Config, SnapshotParser)}.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull PagedList.Config config,
                           @NonNull SnapshotParser<T> parser) {
    return setQuery(query, Source.DEFAULT, config, parser);
}
 
Example #23
Source File: FirestorePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the query using a custom {@link Source} and a {@link ClassSnapshotParser} based
 * on the given class.
 *
 * See {@link #setQuery(Query, Source, PagedList.Config, SnapshotParser)}.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull Source source,
                           @NonNull PagedList.Config config,
                           @NonNull Class<T> modelClass) {
    return setQuery(query, source, config, new ClassSnapshotParser<>(modelClass));
}
 
Example #24
Source File: FirestorePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the Firestore query to paginate.
 *
 * @param query the Firestore query. This query should only contain where() and
 *              orderBy() clauses. Any limit() or pagination clauses will cause errors.
 * @param source the data source to use for query data.
 * @param config paging configuration, passed directly to the support paging library.
 * @param parser the {@link SnapshotParser} to parse {@link DocumentSnapshot} into model
 *               objects.
 * @return this, for chaining.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query,
                           @NonNull Source source,
                           @NonNull PagedList.Config config,
                           @NonNull SnapshotParser<T> parser) {
    // Build paged list
    FirestoreDataSource.Factory factory = new FirestoreDataSource.Factory(query, source);
    mData = new LivePagedListBuilder<>(factory, config).build();

    mParser = parser;
    return this;
}
 
Example #25
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 4 votes vote down vote up
public void queryStartAtEndAt() {
    // [START query_start_at_single]
    // Get all cities with a population >= 1,000,000, ordered by population,
    db.collection("cities")
            .orderBy("population")
            .startAt(1000000);
    // [END query_start_at_single]

    // [START query_end_at_single]
    // Get all cities with a population <= 1,000,000, ordered by population,
    db.collection("cities")
            .orderBy("population")
            .endAt(1000000);
    // [END query_end_at_single]

    // [START query_start_at_doc_snapshot]
    // Get the data for "San Francisco"
    db.collection("cities").document("SF")
            .get()
            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                @Override
                public void onSuccess(DocumentSnapshot documentSnapshot) {
                    // Get all cities with a population bigger than San Francisco.
                    Query biggerThanSf = db.collection("cities")
                            .orderBy("population")
                            .startAt(documentSnapshot);

                    // ...
                }
            });
    // [END query_start_at_doc_snapshot]

    // [START query_pagination]
    // Construct query for first 25 cities, ordered by population
    Query first = db.collection("cities")
            .orderBy("population")
            .limit(25);

    first.get()
        .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot documentSnapshots) {
                // ...

                // Get the last visible document
                DocumentSnapshot lastVisible = documentSnapshots.getDocuments()
                        .get(documentSnapshots.size() -1);

                // Construct a new query starting at this document,
                // get the next 25 cities.
                Query next = db.collection("cities")
                        .orderBy("population")
                        .startAfter(lastVisible)
                        .limit(25);

                // Use the query for pagination
                // ...
            }
        });
    // [END query_pagination]

    // [START multi_cursor]
    // Will return all Springfields
    db.collection("cities")
            .orderBy("name")
            .orderBy("state")
            .startAt("Springfield");

    // Will return "Springfield, Missouri" and "Springfield, Wisconsin"
    db.collection("cities")
            .orderBy("name")
            .orderBy("state")
            .startAt("Springfield", "Missouri");
    // [END multi_cursor]
}
 
Example #26
Source File: FirestoreAdapter.java    From quickstart-android with Apache License 2.0 4 votes vote down vote up
public FirestoreAdapter(Query query) {
    mQuery = query;
}
 
Example #27
Source File: FirestoreRecyclerOptions.java    From FirebaseUI-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Calls {@link #setQuery(Query, MetadataChanges, Class)} with metadata changes excluded.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query, @NonNull SnapshotParser<T> parser) {
    return setQuery(query, MetadataChanges.EXCLUDE, parser);
}
 
Example #28
Source File: FirestoreRecyclerOptions.java    From FirebaseUI-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Calls {@link #setQuery(Query, MetadataChanges, Class)} with metadata changes excluded.
 */
@NonNull
public Builder<T> setQuery(@NonNull Query query, @NonNull Class<T> modelClass) {
    return setQuery(query, MetadataChanges.EXCLUDE, modelClass);
}
 
Example #29
Source File: FirestoreDataSource.java    From FirebaseUI-Android with Apache License 2.0 4 votes vote down vote up
public Factory(@NonNull Query query, @NonNull Source source) {
    mQuery = query;
    mSource = source;
}
 
Example #30
Source File: FirestorePagingActivity.java    From FirebaseUI-Android with Apache License 2.0 4 votes vote down vote up
private void setUpAdapter() {
    Query baseQuery = mItemsCollection.orderBy("value", Query.Direction.ASCENDING);

    PagedList.Config config = new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPrefetchDistance(10)
            .setPageSize(20)
            .build();

    FirestorePagingOptions<Item> options = new FirestorePagingOptions.Builder<Item>()
            .setLifecycleOwner(this)
            .setQuery(baseQuery, config, Item.class)
            .build();

    final FirestorePagingAdapter<Item, ItemViewHolder> adapter =
            new FirestorePagingAdapter<Item, ItemViewHolder>(options) {
                @NonNull
                @Override
                public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
                                                         int viewType) {
                    View view = LayoutInflater.from(parent.getContext())
                            .inflate(R.layout.item_item, parent, false);
                    return new ItemViewHolder(view);
                }

                @Override
                protected void onBindViewHolder(@NonNull ItemViewHolder holder,
                                                int position,
                                                @NonNull Item model) {
                    holder.bind(model);
                }

                @Override
                protected void onLoadingStateChanged(@NonNull LoadingState state) {
                    switch (state) {
                        case LOADING_INITIAL:
                        case LOADING_MORE:
                            mSwipeRefreshLayout.setRefreshing(true);
                            break;
                        case LOADED:
                            mSwipeRefreshLayout.setRefreshing(false);
                            break;
                        case FINISHED:
                            mSwipeRefreshLayout.setRefreshing(false);
                            showToast("Reached end of data set.");
                            break;
                        case ERROR:
                            showToast("An error occurred.");
                            retry();
                            break;
                    }
                }

                @Override
                protected void onError(@NonNull Exception e) {
                    mSwipeRefreshLayout.setRefreshing(false);
                    Log.e(TAG, e.getMessage(), e);
                }
            };

    mRecycler.setLayoutManager(new LinearLayoutManager(this));
    mRecycler.setAdapter(adapter);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            adapter.refresh();
        }
    });
}