com.google.firebase.firestore.QuerySnapshot Java Examples

The following examples show how to use com.google.firebase.firestore.QuerySnapshot. 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: FirestoreQueryOnSubscribe.java    From Track-My-Location with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void subscribe(FlowableEmitter<QuerySnapshot> e) throws Exception {
    QueryEventListener listener = new QueryEventListener(e);
    ListenerRegistration registration = mQuery.addSnapshotListener(listener);
    e.setDisposable(new Disposable() {
        boolean disposed = false;
        @Override
        public void dispose() {
            if (!isDisposed()) {
                registration.remove();
                listener.emitter = null;
                disposed = true;
            }
        }

        @Override
        public boolean isDisposed() {
            return disposed;
        }
    });
}
 
Example #2
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void getMultipleDocs() {
    // [START get_multiple]
    db.collection("cities")
            .whereEqualTo("capital", true)
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
    // [END get_multiple]
}
 
Example #3
Source File: ContactsFirestoreSynchronizer.java    From chat21-android-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<IChatUser> getAllContacts() {
        final List<IChatUser> contacts = new ArrayList<>();

        contactsCollReference.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
//                        contacts.add(document.toObject(ChatUser.class));
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });
        return  null;

    }
 
Example #4
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void getAllDocs() {
    // [START get_multiple_all]
    db.collection("cities")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
    // [END get_multiple_all]
}
 
Example #5
Source File: FirestoreDataSource.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void loadAfter(@NonNull final LoadParams<PageKey> params,
                      @NonNull final LoadCallback<PageKey, DocumentSnapshot> callback) {
    final PageKey key = params.key;

    // Set loading state
    mLoadingState.postValue(LoadingState.LOADING_MORE);

    key.getPageQuery(mBaseQuery, params.requestedLoadSize)
            .get(mSource)
            .addOnSuccessListener(new OnLoadSuccessListener() {
                @Override
                protected void setResult(@NonNull QuerySnapshot snapshot) {
                    PageKey nextPage = getNextPageKey(snapshot);
                    callback.onResult(snapshot.getDocuments(), nextPage);
                }
            })
            .addOnFailureListener(new OnLoadFailureListener() {
                @Override
                protected Runnable getRetryRunnable() {
                    return getRetryLoadAfter(params, callback);
                }
            });

}
 
Example #6
Source File: FirestoreDataSource.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void loadInitial(@NonNull final LoadInitialParams<PageKey> params,
                        @NonNull final LoadInitialCallback<PageKey, DocumentSnapshot> callback) {

    // Set initial loading state
    mLoadingState.postValue(LoadingState.LOADING_INITIAL);

    mBaseQuery.limit(params.requestedLoadSize)
            .get(mSource)
            .addOnSuccessListener(new OnLoadSuccessListener() {
                @Override
                protected void setResult(@NonNull QuerySnapshot snapshot) {
                    PageKey nextPage = getNextPageKey(snapshot);
                    callback.onResult(snapshot.getDocuments(), null, nextPage);
                }
            })
            .addOnFailureListener(new OnLoadFailureListener() {
                @Override
                protected Runnable getRetryRunnable() {
                    return getRetryLoadInitial(params, callback);
                }
            });

}
 
Example #7
Source File: FirestoreArray.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(@Nullable QuerySnapshot snapshots, @Nullable FirebaseFirestoreException e) {
    if (e != null) {
        notifyOnError(e);
        return;
    }

    // Break down each document event
    List<DocumentChange> changes = snapshots.getDocumentChanges(mMetadataChanges);
    for (DocumentChange change : changes) {
        switch (change.getType()) {
            case ADDED:
                onDocumentAdded(change);
                break;
            case REMOVED:
                onDocumentRemoved(change);
                break;
            case MODIFIED:
                onDocumentModified(change);
                break;
        }
    }

    notifyOnDataChanged();
}
 
Example #8
Source File: FirestoreAdapter.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
    if (e != null) {
        Log.w(TAG, "onEvent:error", e);
        onError(e);
        return;
    }

    // Dispatch the event
    Log.d(TAG, "onEvent:numChanges:" + documentSnapshots.getDocumentChanges().size());
    for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
        switch (change.getType()) {
            case ADDED:
                onDocumentAdded(change);
                break;
            case MODIFIED:
                onDocumentModified(change);
                break;
            case REMOVED:
                onDocumentRemoved(change);
                break;
        }
    }

    onDataChanged();
}
 
Example #9
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void offlineListen(FirebaseFirestore db) {
    // [START offline_listen]
    db.collection("cities").whereEqualTo("state", "CA")
            .addSnapshotListener(MetadataChanges.INCLUDE, new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot querySnapshot,
                                    @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
                        Log.w(TAG, "Listen error", e);
                        return;
                    }

                    for (DocumentChange change : querySnapshot.getDocumentChanges()) {
                        if (change.getType() == Type.ADDED) {
                            Log.d(TAG, "New city:" + change.getDocument().getData());
                        }

                        String source = querySnapshot.getMetadata().isFromCache() ?
                                "local cache" : "server";
                        Log.d(TAG, "Data fetched from " + source);
                    }

                }
            });
    // [END offline_listen]
}
 
Example #10
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void listenToMultiple() {
    // [START listen_multiple]
    db.collection("cities")
            .whereEqualTo("state", "CA")
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot value,
                                    @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
                        Log.w(TAG, "Listen failed.", e);
                        return;
                    }

                    List<String> cities = new ArrayList<>();
                    for (QueryDocumentSnapshot doc : value) {
                        if (doc.get("name") != null) {
                            cities.add(doc.getString("name"));
                        }
                    }
                    Log.d(TAG, "Current cites in CA: " + cities);
                }
            });
    // [END listen_multiple]
}
 
Example #11
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void getAllUsers() {
    // [START get_all_users]
    db.collection("users")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.w(TAG, "Error getting documents.", task.getException());
                    }
                }
            });
    // [END get_all_users]
}
 
Example #12
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void listenForUsers() {
    // [START listen_for_users]
    // Listen for users born before 1900.
    //
    // You will get a first snapshot with the initial results and a new
    // snapshot each time there is a change in the results.
    db.collection("users")
            .whereLessThan("born", 1900)
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot snapshots,
                                    @Nullable FirebaseFirestoreException e) {

                    if (e != null) {
                        Log.w(TAG, "Listen failed.", e);
                        return;
                    }

                    Log.d(TAG, "Current users born before 1900: " + snapshots);
                }
            });
    // [END listen_for_users]
}
 
Example #13
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void handleListenErrors() {
    // [START handle_listen_errors]
    db.collection("cities")
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot snapshots,
                                    @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
                        Log.w(TAG, "listen:error", e);
                        return;
                    }

                    for (DocumentChange dc : snapshots.getDocumentChanges()) {
                        if (dc.getType() == Type.ADDED) {
                            Log.d(TAG, "New city: " + dc.getDocument().getData());
                        }
                    }

                }
            });
    // [END handle_listen_errors]
}
 
Example #14
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 #15
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 #16
Source File: ThreadsListFragmentPresenter.java    From demo-firebase-android with The Unlicense 5 votes vote down vote up
private void updateThreads(QuerySnapshot documentSnapshots, Task<DocumentSnapshot> task) {
    if (task.isSuccessful()) {
        DocumentSnapshot documentSnapshot = task.getResult();

        DefaultUser defaultUser = documentSnapshot.toObject(DefaultUser.class);
        defaultUser.setName(documentSnapshot.getId());

        List<DefaultChatThread> threads = new ArrayList<>();

        for (String channelId : defaultUser.getChannels()) {
            for (DocumentSnapshot document : documentSnapshots) {
                if (document.getId().equals(channelId)) {
                    List<String> members = (List<String>) document.get(KEY_PROPERTY_MEMBERS);
                    long messagesCount = (Long) document.get(KEY_PROPERTY_COUNT);

                    String senderId = members.get(0).equals(firebaseAuth.getCurrentUser()
                                                                        .getEmail()
                                                                        .toLowerCase()
                                                                        .split("@")[0])
                                      ? members.get(0) : members.get(1);
                    String receiverId = members.get(0)
                                               .equals(senderId) ? members.get(1)
                                                                 : members.get(0);
                    threads.add(new DefaultChatThread(document.getId(),
                                                      senderId,
                                                      receiverId,
                                                      messagesCount));
                }
            }
        }

        onDataReceivedInteractor.onDataReceived(threads);
    } else {
        onDataReceivedInteractor.onDataReceivedError(task.getException());
    }
}
 
Example #17
Source File: RecordsCollectionReference.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@NotNull
private ImmutableList<ValueOrError<Observation>> convert(
    QuerySnapshot querySnapshot, Feature feature) {
  return stream(querySnapshot.getDocuments())
      .map(doc -> ValueOrError.create(() -> ObservationConverter.toObservation(feature, doc)))
      .collect(toImmutableList());
}
 
Example #18
Source File: SolutionCounters.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public Task<Integer> getCount(final DocumentReference ref) {
    // Sum the count of each shard in the subcollection
    return ref.collection("shards").get()
            .continueWith(new Continuation<QuerySnapshot, Integer>() {
                @Override
                public Integer then(@NonNull Task<QuerySnapshot> task) throws Exception {
                    int count = 0;
                    for (DocumentSnapshot snap : task.getResult()) {
                        Shard shard = snap.toObject(Shard.class);
                        count += shard.count;
                    }
                    return count;
                }
            });
}
 
Example #19
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void listenState() {
    // [START listen_state]
    db.collection("cities")
            .whereEqualTo("state", "CA")
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot snapshots,
                                    @Nullable FirebaseFirestoreException e) {

                    if (e != null) {
                        Log.w(TAG, "listen:error", e);
                        return;
                    }

                    for (DocumentChange dc : snapshots.getDocumentChanges()) {
                        if (dc.getType() == Type.ADDED) {
                            Log.d(TAG, "New city: " + dc.getDocument().getData());
                        }
                    }

                    if (!snapshots.getMetadata().isFromCache()) {
                        Log.d(TAG, "Got initial state.");
                    }
                }
            });
    // [END listen_state]
}
 
Example #20
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void collectionGroupQuery() {
    // [START fs_collection_group_query]
    db.collectionGroup("landmarks").whereEqualTo("type", "museum").get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    // [START_EXCLUDE]
                    for (QueryDocumentSnapshot snap : queryDocumentSnapshots) {
                        Log.d(TAG, snap.getId() + " => " + snap.getData());
                    }
                    // [END_EXCLUDE]
                }
            });
    // [END fs_collection_group_query]
}
 
Example #21
Source File: FluentFirestore.java    From ground-android with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the provided mapping function to each document in the specified query snapshot, if
 * present. If no results are present, completes with an empty list.
 */
static <T> Single<List<T>> toSingleList(
    Maybe<QuerySnapshot> result, Function<DocumentSnapshot, T> mappingFunction) {
  return result
      .map(
          querySnapshot ->
              stream(querySnapshot.getDocuments()).map(mappingFunction).collect(toList()))
      .toSingle(Collections.emptyList());
}
 
Example #22
Source File: SolutionArrays.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void queryForCats() {
    // [START query_for_cats]
    db.collection("posts")
            .whereEqualTo("categories.cats", true)
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                // [START_EXCLUDE]
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {}
                // [END_EXCLUDE]
            });
    // [END query_for_cats]
}
 
Example #23
Source File: FirestoreQueryOnSubscribe.java    From Track-My-Location with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
    if (e != null) {
        emitter.onError(e);
    } else {
        emitter.onNext(documentSnapshots);
    }
}
 
Example #24
Source File: IntegrationTestUtil.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public static List<Map<String, Object>> querySnapshotToValues(QuerySnapshot querySnapshot) {
  List<Map<String, Object>> res = new ArrayList<>();
  for (DocumentSnapshot doc : querySnapshot) {
    res.add(doc.getData());
  }
  return res;
}
 
Example #25
Source File: UserParser.java    From ridesharing-android with MIT License 5 votes vote down vote up
@NonNull
@Override
public List<User> parse(QuerySnapshot querySnapshot) {
    List<User> users = new ArrayList<>();
    if (querySnapshot != null) {
        for (QueryDocumentSnapshot doc : querySnapshot) {
            users.add(parse(doc));
        }
    }
    return users;
}
 
Example #26
Source File: OrderParser.java    From ridesharing-android with MIT License 5 votes vote down vote up
@NonNull
@Override
public List<Order> parse(QuerySnapshot querySnapshot) {
    List<Order> orders = new ArrayList<>();
    if (querySnapshot != null) {
        for (QueryDocumentSnapshot doc : querySnapshot) {
            orders.add(parse(doc));
        }
    }
    return orders;
}
 
Example #27
Source File: QueryLiveData.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
@NonNull
private List<T> documentToList(QuerySnapshot snapshots) {
    final List<T> retList = new ArrayList<>();
    if (snapshots.isEmpty()) {
        return retList;
    }

    for (DocumentSnapshot document : snapshots.getDocuments()) {
        retList.add(document.toObject(type).withId(document.getId()));
    }

    return retList;
}
 
Example #28
Source File: DriverMapPresenter.java    From ridesharing-android with MIT License 5 votes vote down vote up
private void subscribeNewOrderUpdates() {
    if (newOrderListenerRegistration != null) {
        newOrderListenerRegistration.remove();
    }
    newOrderListenerRegistration = db.collection("orders")
            .whereIn("status", Arrays.asList(Order.NEW, Order.CANCELLED))
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @SuppressWarnings("ConstantConditions")
                @Override
                public void onEvent(@Nullable QuerySnapshot value,
                                    @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
                        Log.w(TAG, "Listen failed.", e);
                        return;
                    }

                    if (value != null) {
                        List<Order> orders = new ArrayList<>();
                        OrderParser parser = new OrderParser();
                        for (QueryDocumentSnapshot doc : value) {
                            if (Order.CANCELLED.equals(doc.getString("status"))) {
                                if (mState.newOrders.containsKey(doc.getId())) {
                                    mState.newOrders.remove(doc.getId()).marker.remove();
                                }
                                continue;
                            }

                            Order order = parser.parse(doc);
                            orders.add(order);
                        }
                        updateNewOrders(orders);
                    }
                }
            });
}
 
Example #29
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 #30
Source File: QueryLiveData.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(QuerySnapshot snapshots, FirebaseFirestoreException e) {
    if (e != null) {
        setValue(new Resource<>(e));
        return;
    }
    setValue(new Resource<>(documentToList(snapshots)));
}