com.google.firebase.firestore.EventListener Java Examples

The following examples show how to use com.google.firebase.firestore.EventListener. 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 7 votes vote down vote up
public void listenToDocument() {
    // [START listen_document]
    final DocumentReference docRef = db.collection("cities").document("SF");
    docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@Nullable DocumentSnapshot snapshot,
                            @Nullable FirebaseFirestoreException e) {
            if (e != null) {
                Log.w(TAG, "Listen failed.", e);
                return;
            }

            if (snapshot != null && snapshot.exists()) {
                Log.d(TAG, "Current data: " + snapshot.getData());
            } else {
                Log.d(TAG, "Current data: null");
            }
        }
    });
    // [END listen_document]
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void listenToDocumentLocal() {
    // [START listen_document_local]
    final DocumentReference docRef = db.collection("cities").document("SF");
    docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@Nullable DocumentSnapshot snapshot,
                            @Nullable FirebaseFirestoreException e) {
            if (e != null) {
                Log.w(TAG, "Listen failed.", e);
                return;
            }

            String source = snapshot != null && snapshot.getMetadata().hasPendingWrites()
                    ? "Local" : "Server";

            if (snapshot != null && snapshot.exists()) {
                Log.d(TAG, source + " data: " + snapshot.getData());
            } else {
                Log.d(TAG, source + " data: null");
            }
        }
    });
    // [END listen_document_local]
}
 
Example #7
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 #8
Source File: SpecTestCase.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private void doRemoveSnapshotsInSyncListener() throws Exception {
  if (snapshotsInSyncListeners.size() == 0) {
    throw Assert.fail("There must be a listener to unlisten to");
  } else {
    EventListener<Void> listenerToRemove = snapshotsInSyncListeners.remove(0);
    eventManager.removeSnapshotsInSyncListener(listenerToRemove);
  }
}
 
Example #9
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 #10
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void listenToDiffs() {
    // [START listen_diffs]
    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()) {
                        switch (dc.getType()) {
                            case ADDED:
                                Log.d(TAG, "New city: " + dc.getDocument().getData());
                                break;
                            case MODIFIED:
                                Log.d(TAG, "Modified city: " + dc.getDocument().getData());
                                break;
                            case REMOVED:
                                Log.d(TAG, "Removed city: " + dc.getDocument().getData());
                                break;
                        }
                    }

                }
            });
    // [END listen_diffs]
}
 
Example #11
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void listenWithMetadata() {
    // [START listen_with_metadata]
    // Listen for metadata changes to the document.
    DocumentReference docRef = db.collection("cities").document("SF");
    docRef.addSnapshotListener(MetadataChanges.INCLUDE, new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@Nullable DocumentSnapshot snapshot,
                            @Nullable FirebaseFirestoreException e) {
            // ...
        }
    });
    // [END listen_with_metadata]
}
 
Example #12
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 #13
Source File: EventAccumulator.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public EventListener<T> listener() {
  return (value, error) -> {
    synchronized (EventAccumulator.this) {
      hardAssert(error == null, "Unexpected error: %s", error);
      Log.i("EventAccumulator", "Received new event: " + value);
      events.add(value);
      checkFulfilled();
    }
  };
}
 
Example #14
Source File: FirestoreClient.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public void removeSnapshotsInSyncListener(EventListener<Void> listener) {
  // Checks for shutdown but does not raise error, allowing remove after shutdown to be a no-op.
  if (isTerminated()) {
    return;
  }
  asyncQueue.enqueueAndForget(() -> eventManager.removeSnapshotsInSyncListener(listener));
}
 
Example #15
Source File: FirestoreClient.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Starts listening to a query. */
public QueryListener listen(
    Query query, ListenOptions options, EventListener<ViewSnapshot> listener) {
  this.verifyNotTerminated();
  QueryListener queryListener = new QueryListener(query, options, listener);
  asyncQueue.enqueueAndForget(() -> eventManager.addQueryListener(queryListener));
  return queryListener;
}
 
Example #16
Source File: SpecTestCase.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
private void doAddSnapshotsInSyncListener() {
  EventListener<Void> eventListener =
      (Void v, FirebaseFirestoreException error) -> snapshotsInSyncEvents += 1;
  snapshotsInSyncListeners.add(eventListener);
  eventManager.addSnapshotsInSyncListener(eventListener);
}
 
Example #17
Source File: MessageHistory.java    From Hify with MIT License 4 votes vote down vote up
public void getTextMessage(){

        refreshLayout.setRefreshing(true);
        getView().findViewById(R.id.default_item).setVisibility(View.GONE);
        mFirestore.collection("Users")
                .document(mAuth.getCurrentUser().getUid())
                .collection("Notifications")
                .orderBy("timestamp", Query.Direction.DESCENDING)
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {

                        if(e!=null){
                            refreshLayout.setRefreshing(false);
                            Toasty.error(getView().getContext(), "Some technical error occurred", Toasty.LENGTH_SHORT, true).show();
                            Log.w("error","listen",e);
                            return;
                        }

                        if(!queryDocumentSnapshots.isEmpty()){

                            for(DocumentChange doc:queryDocumentSnapshots.getDocumentChanges()) {

                                if (doc.getType() == DocumentChange.Type.ADDED) {

                                    Message message = doc.getDocument().toObject(Message.class).withId(doc.getDocument().getId());
                                    messages.add(message);
                                    messageTextAdapter.notifyDataSetChanged();
                                    refreshLayout.setRefreshing(false);

                                }

                            }

                            if(messages.isEmpty()){
                                refreshLayout.setRefreshing(false);
                                getView().findViewById(R.id.default_item).setVisibility(View.VISIBLE);
                            }

                        }else {
                            refreshLayout.setRefreshing(false);
                            getView().findViewById(R.id.default_item).setVisibility(View.VISIBLE);
                        }

                    }
                });

    }
 
Example #18
Source File: RiderMapPresenter.java    From ridesharing-android with MIT License 4 votes vote down vote up
private void subscribeDriverUpdates() {
    if (driversListenerRegistration != null) {
        driversListenerRegistration.remove();
    }
    driversListenerRegistration = db.collection("users")
            .whereEqualTo("role", User.USER_ROLE_DRIVER)
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot value,
                                    @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
                        Log.w(TAG, "Listen failed.", e);
                        return;
                    }

                    if (value != null) {
                        UserParser parser = new UserParser();
                        for (QueryDocumentSnapshot doc : value) {
                            User driver = mState.drivers.get(doc.getId());
                            if (driver == null) {
                                final User newDriver = parser.parse(doc);
                                if (newDriver != null && !TextUtils.isEmpty(newDriver.deviceId)) {
                                    newDriver.deviceUpdatesHandler = new MyDeviceUpdatesHandler() {
                                        @Override
                                        public void onLocationUpdateReceived(@NonNull Location location) {
                                            newDriver.location = location;
                                            if (newDriver.marker == null) {
                                                newDriver.marker = mView.addMarker(newDriver);
                                            } else {
                                                newDriver.marker.setRotation(newDriver.location.getBearing());
                                                newDriver.marker.setPosition(
                                                        new LatLng(newDriver.location.getLatitude(), newDriver.location.getLongitude())
                                                );
                                            }
                                        }
                                    };
                                    hyperTrackViews.subscribeToDeviceUpdates(newDriver.deviceId, newDriver.deviceUpdatesHandler);
                                    mState.drivers.put(newDriver.id, newDriver);
                                }
                            }
                        }
                    }
                }
            });
}
 
Example #19
Source File: QueryListener.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public QueryListener(
    Query query, EventManager.ListenOptions options, EventListener<ViewSnapshot> listener) {
  this.query = query;
  this.listener = listener;
  this.options = options;
}
 
Example #20
Source File: SolutionRateLimiting.java    From snippets-android with Apache License 2.0 4 votes vote down vote up
public void startUpdates() {
    String deviceId = "my-device-id";
    final DocumentReference reference = db.collection("readings").document(deviceId);

    // Listen to the document, including metadata changes so we get notified
    // when writes have propagated to the server.
    mRegistration = reference.addSnapshotListener(MetadataChanges.INCLUDE, new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@Nullable DocumentSnapshot documentSnapshot,
                            @Nullable FirebaseFirestoreException e) {
            if (e != null) {
                Log.w(TAG, "onEvent:error", e);
            }

            if (documentSnapshot != null && !documentSnapshot.getMetadata().hasPendingWrites()) {
                Log.d(TAG, "Got server snapshot.");
               mReadyForUpdate = true;
            }
        }
    });

    // On a regular interval, attempt to update the document. Only perform the update
    // if we have gotten a snapshot from the server since the last update, which means
    // we are ready to update again.
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (mReadyForUpdate) {
                Log.d(TAG, "Updating sensor data");

                // Update the document
                Map<String, Object> updates = new HashMap<>();
                updates.put("temperature", getCurrentTemperature());
                updates.put("timestamp", FieldValue.serverTimestamp());
                reference.set(updates, SetOptions.merge());


                // Mark 'ready for update' as false until we get the next snapshot from the server
                mReadyForUpdate = false;
            } else {
                Log.d(TAG, "Not ready for update");
            }

            // Schedule the next update
            mHandler.postDelayed(this, UPDATE_INTERVAL_MS);
        }
    }, UPDATE_INTERVAL_MS);
}
 
Example #21
Source File: AsyncEventListener.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public AsyncEventListener(Executor executor, EventListener<T> eventListener) {
  this.executor = executor;
  this.eventListener = eventListener;
}
 
Example #22
Source File: FirestoreClient.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public void addSnapshotsInSyncListener(EventListener<Void> listener) {
  verifyNotTerminated();
  asyncQueue.enqueueAndForget(() -> eventManager.addSnapshotsInSyncListener(listener));
}
 
Example #23
Source File: EventManager.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
/** Call all global snapshot listeners that have been set. */
private void raiseSnapshotsInSyncEvent() {
  for (EventListener<Void> listener : snapshotsInSyncListeners) {
    listener.onEvent(null, null);
  }
}
 
Example #24
Source File: EventManager.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public void removeSnapshotsInSyncListener(EventListener<Void> listener) {
  snapshotsInSyncListeners.remove(listener);
}
 
Example #25
Source File: EventManager.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public void addSnapshotsInSyncListener(EventListener<Void> listener) {
  snapshotsInSyncListeners.add(listener);
  listener.onEvent(null, null);
}
 
Example #26
Source File: AnswersActivity.java    From Hify with MIT License 4 votes vote down vote up
private void getAnswers() {

        answers.clear();
        refreshLayout.setRefreshing(true);
        findViewById(R.id.default_item).setVisibility(View.GONE);

        mFirestore.collection("Answers")
                .orderBy("timestamp", Query.Direction.DESCENDING)
                .whereEqualTo("question_id",doc_id)
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {

                        if(e!=null){
                            refreshLayout.setRefreshing(false);
                            Log.e(TAG,e.getLocalizedMessage());
                            return;
                        }

                        if(queryDocumentSnapshots.isEmpty()){
                            refreshLayout.setRefreshing(false);
                            findViewById(R.id.default_item).setVisibility(View.VISIBLE);
                        }else{
                            for(DocumentChange doc:queryDocumentSnapshots.getDocumentChanges()) {

                                if (doc.getType() == DocumentChange.Type.ADDED) {

                                    refreshLayout.setRefreshing(false);
                                    Answers answer = doc.getDocument().toObject(Answers.class).withId(doc.getDocument().getId());
                                    if (doc.getDocument().getString("is_answer").toLowerCase().equals("yes")) {
                                        answers.add(0, answer);
                                    } else {
                                        answers.add(answer);
                                    }
                                    adapter.notifyDataSetChanged();


                                }

                            }
                        }

                    }
                });

    }
 
Example #27
Source File: AllQuestions.java    From Hify with MIT License 4 votes vote down vote up
public void filterResult(String subject){

        if(subject.equals("All")){
            getQuestions();
        }else{

            refreshLayout.setRefreshing(true);
            getView().findViewById(R.id.default_item).setVisibility(View.GONE);

            Query firstQuery = mFirestore.collection("Questions")
                    .whereEqualTo("subject",subject)
                    .orderBy("timestamp", Query.Direction.DESCENDING);
            firstQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                    try {

                        if (!documentSnapshots.isEmpty()) {

                            for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {

                                if (doc.getType() == DocumentChange.Type.ADDED) {

                                    if (!doc.getDocument().getString("id").equals(mCurrentUser.getUid())) {
                                        AllQuestionsModel question = doc.getDocument().toObject(AllQuestionsModel.class).withId(doc.getDocument().getId());
                                        allQuestionsModelList.add(question);
                                        adapter.notifyDataSetChanged();
                                        refreshLayout.setRefreshing(false);
                                    }

                                }



                            }
                            if(allQuestionsModelList.isEmpty()){
                                getView().findViewById(R.id.default_item).setVisibility(View.VISIBLE);
                                refreshLayout.setRefreshing(false);
                            }

                        } else {
                            getView().findViewById(R.id.default_item).setVisibility(View.VISIBLE);
                            refreshLayout.setRefreshing(false);
                        }
                    }catch (NullPointerException eee){
                        Toasty.error(context, "Some technical error occurred", Toasty.LENGTH_SHORT,true).show();
                        adapter.notifyDataSetChanged();
                        if(allQuestionsModelList.isEmpty()){
                            getView().findViewById(R.id.default_item).setVisibility(View.VISIBLE);
                            refreshLayout.setRefreshing(false);
                        }
                    } catch (Exception ee){
                        ee.printStackTrace();
                        Toasty.error(context, "Some technical error occurred", Toasty.LENGTH_SHORT, true).show();
                        if(allQuestionsModelList.isEmpty()){
                            refreshLayout.setRefreshing(false);
                            getView().findViewById(R.id.default_item).setVisibility(View.VISIBLE);
                        }
                    }

                }

            });


        }

    }
 
Example #28
Source File: AllQuestions.java    From Hify with MIT License 4 votes vote down vote up
private void getQuestions() {

        getView().findViewById(R.id.default_item).setVisibility(View.GONE);
        refreshLayout.setRefreshing(true);
        Query firstQuery = mFirestore.collection("Questions")
                .orderBy("timestamp", Query.Direction.DESCENDING);
        firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                if (!documentSnapshots.isEmpty()) {

                    for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {

                        if (doc.getType() == DocumentChange.Type.ADDED) {

                            if (!doc.getDocument().getString("id").equals(mCurrentUser.getUid())) {
                                AllQuestionsModel question = doc.getDocument().toObject(AllQuestionsModel.class).withId(doc.getDocument().getId());
                                allQuestionsModelList.add(question);
                                adapter.notifyDataSetChanged();
                                refreshLayout.setRefreshing(false);
                            }

                        }

                    }

                    if(allQuestionsModelList.isEmpty()){
                        getView().findViewById(R.id.default_item).setVisibility(View.VISIBLE);
                        refreshLayout.setRefreshing(false);
                    }

                } else {
                    getView().findViewById(R.id.default_item).setVisibility(View.VISIBLE);
                    refreshLayout.setRefreshing(false);
                }

            }

        });


    }