com.google.firebase.firestore.FirebaseFirestoreException Java Examples

The following examples show how to use com.google.firebase.firestore.FirebaseFirestoreException. 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: Transaction.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Takes a set of keys and asynchronously attempts to fetch all the documents from the backend,
 * ignoring any local changes.
 */
public Task<List<MaybeDocument>> lookup(List<DocumentKey> keys) {
  ensureCommitNotCalled();

  if (mutations.size() != 0) {
    return Tasks.forException(
        new FirebaseFirestoreException(
            "Firestore transactions require all reads to be executed before all writes.",
            Code.INVALID_ARGUMENT));
  }
  return datastore
      .lookup(keys)
      .continueWithTask(
          Executors.DIRECT_EXECUTOR,
          task -> {
            if (task.isSuccessful()) {
              for (MaybeDocument doc : task.getResult()) {
                recordVersion(doc);
              }
            }
            return task;
          });
}
 
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: StageRepository.java    From triviums with MIT License 6 votes vote down vote up
private void fetchProgress(String categoryName, ProgressCallback callback) {
    DocumentReference docRef = firestore.collection("users")
            .document(userProfile.getUserUid())
            .collection("categories")
            .document("category")
            .collection("progress")
            .document(categoryName);

    docRef.get().addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
        }
        try {
            callback.onCallback(new FirestoreResultResponse(task.getResult().getData(), null));
        } catch (Exception e) {
            if (e instanceof FirebaseFirestoreException) {
                callback.onCallback(new FirestoreResultResponse(null, e.getLocalizedMessage()));
            }
            e.printStackTrace();
        }
    })
            .addOnFailureListener(error -> {
                callback.onCallback(new FirestoreResultResponse(null, error.toString()));
            });

}
 
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: 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 #7
Source File: FirestoreClient.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public Task<Document> getDocumentFromLocalCache(DocumentKey docKey) {
  this.verifyNotTerminated();
  return asyncQueue
      .enqueue(() -> localStore.readDocument(docKey))
      .continueWith(
          (result) -> {
            @Nullable MaybeDocument maybeDoc = result.getResult();

            if (maybeDoc instanceof Document) {
              return (Document) maybeDoc;
            } else if (maybeDoc instanceof NoDocument) {
              return null;
            } else {
              throw new FirebaseFirestoreException(
                  "Failed to get document from cache. (However, this document may exist on the "
                      + "server. Run again without setting source to CACHE to attempt "
                      + "to retrieve the document from the server.)",
                  Code.UNAVAILABLE);
            }
          });
}
 
Example #8
Source File: Transaction.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the precondition for a document if the operation is an update, based on the provided
 * UpdateOptions.
 */
private Precondition preconditionForUpdate(DocumentKey key) throws FirebaseFirestoreException {
  @Nullable SnapshotVersion version = this.readVersions.get(key);
  // The first time a document is written, we want to take into account the read time and
  // existence.
  if (!writtenDocs.contains(key) && version != null) {
    if (version != null && version.equals(SnapshotVersion.NONE)) {
      // The document to update doesn't exist, so fail the transaction.
      //
      // This has to be validated locally because you can't send a precondition that a document
      // does not exist without changing the semantics of the backend write to be an insert. This
      // is the reverse of what we want, since we want to assert that the document doesn't exist
      // but then send the update and have it fail. Since we can't express that to the backend, we
      // have to validate locally.
      //
      // Note: this can change once we can send separate verify writes in the transaction.
      throw new FirebaseFirestoreException(
          "Can't update a document that doesn't exist.", Code.INVALID_ARGUMENT);
    }
    // Document exists, base precondition on document update time.
    return Precondition.updateTime(version);
  } else {
    // Document was not read, so we just use the preconditions for a blind write.
    return Precondition.exists(true);
  }
}
 
Example #9
Source File: Transaction.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private void recordVersion(MaybeDocument doc) throws FirebaseFirestoreException {
  SnapshotVersion docVersion;
  if (doc instanceof Document) {
    docVersion = doc.getVersion();
  } else if (doc instanceof NoDocument) {
    // For nonexistent docs, we must use precondition with version 0 when we overwrite them.
    docVersion = SnapshotVersion.NONE;
  } else {
    throw fail("Unexpected document type in transaction: " + doc.getClass().getCanonicalName());
  }

  if (readVersions.containsKey(doc.getKey())) {
    SnapshotVersion existingVersion = readVersions.get(doc.getKey());
    if (!existingVersion.equals(doc.getVersion())) {
      // This transaction will fail no matter what.
      throw new FirebaseFirestoreException(
          "Document version changed between two reads.", Code.ABORTED);
    }
  } else {
    readVersions.put(doc.getKey(), docVersion);
  }
}
 
Example #10
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 #11
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 #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: SQLitePersistence.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public static void clearPersistence(Context context, DatabaseId databaseId, String persistenceKey)
    throws FirebaseFirestoreException {
  String databaseName = SQLitePersistence.databaseName(persistenceKey, databaseId);
  String sqLitePath = context.getDatabasePath(databaseName).getPath();
  String journalPath = sqLitePath + "-journal";
  String walPath = sqLitePath + "-wal";

  File sqLiteFile = new File(sqLitePath);
  File journalFile = new File(journalPath);
  File walFile = new File(walPath);

  try {
    FileUtil.delete(sqLiteFile);
    FileUtil.delete(journalFile);
    FileUtil.delete(walFile);
  } catch (IOException e) {
    throw new FirebaseFirestoreException("Failed to clear persistence." + e, Code.UNKNOWN);
  }
}
 
Example #14
Source File: FirestoreTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void setShouldFailWithPermissionDenied() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseFirestore firestore = FirebaseFirestore.getInstance();

  auth.signOut();
  Thread.sleep(1000); // TODO(allisonbm92): Introduce a better means to reduce flakes.
  DocumentReference doc = firestore.collection("restaurants").document(TestId.create());
  try {
    HashMap<String, Object> data = new HashMap<>();
    data.put("popularity", 5000L);

    Task<?> setTask = doc.set(new HashMap<>(data));
    Throwable failure = Tasks2.waitForFailure(setTask);
    FirebaseFirestoreException ex = (FirebaseFirestoreException) failure;

    assertThat(ex.getCode()).isEqualTo(FirebaseFirestoreException.Code.PERMISSION_DENIED);
  } finally {
    Tasks2.waitBestEffort(doc.delete());
  }
}
 
Example #15
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 #16
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 #17
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 #18
Source File: RestaurantDetailActivity.java    From friendlyeats-android with Apache License 2.0 5 votes vote down vote up
/**
 * Listener for the Restaurant document ({@link #mRestaurantRef}).
 */
@Override
public void onEvent(DocumentSnapshot snapshot, FirebaseFirestoreException e) {
    if (e != null) {
        Log.w(TAG, "restaurant:onEvent", e);
        return;
    }

    onRestaurantLoaded(snapshot.toObject(Restaurant.class));
}
 
Example #19
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 #20
Source File: MainActivity.java    From friendlyeats-android with Apache License 2.0 5 votes vote down vote up
private void initRecyclerView() {
    if (mQuery == null) {
        Log.w(TAG, "No query, not initializing RecyclerView");
    }

    mAdapter = new RestaurantAdapter(mQuery, this) {

        @Override
        protected void onDataChanged() {
            // Show/hide content if the query returns empty.
            if (getItemCount() == 0) {
                mRestaurantsRecycler.setVisibility(View.GONE);
                mEmptyView.setVisibility(View.VISIBLE);
            } else {
                mRestaurantsRecycler.setVisibility(View.VISIBLE);
                mEmptyView.setVisibility(View.GONE);
            }
        }

        @Override
        protected void onError(FirebaseFirestoreException e) {
            // Show a snackbar on errors
            Snackbar.make(findViewById(android.R.id.content),
                    "Error: check logs for info.", Snackbar.LENGTH_LONG).show();
        }
    };

    mRestaurantsRecycler.setLayoutManager(new LinearLayoutManager(this));
    mRestaurantsRecycler.setAdapter(mAdapter);
}
 
Example #21
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void transactions() {
    // [START transactions]
    final DocumentReference sfDocRef = db.collection("cities").document("SF");

    db.runTransaction(new Transaction.Function<Void>() {
        @Override
        public Void apply(Transaction transaction) throws FirebaseFirestoreException {
            DocumentSnapshot snapshot = transaction.get(sfDocRef);

            // Note: this could be done without a transaction
            //       by updating the population using FieldValue.increment()
            double newPopulation = snapshot.getDouble("population") + 1;
            transaction.update(sfDocRef, "population", newPopulation);

            // Success
            return null;
        }
    }).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "Transaction success!");
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Transaction failure.", e);
        }
    });
    // [END transactions]
}
 
Example #22
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void transactionPromise() {
    // [START transaction_with_result]
    final DocumentReference sfDocRef = db.collection("cities").document("SF");

    db.runTransaction(new Transaction.Function<Double>() {
        @Override
        public Double apply(Transaction transaction) throws FirebaseFirestoreException {
            DocumentSnapshot snapshot = transaction.get(sfDocRef);
            double newPopulation = snapshot.getDouble("population") + 1;
            if (newPopulation <= 1000000) {
                transaction.update(sfDocRef, "population", newPopulation);
                return newPopulation;
            } else {
                throw new FirebaseFirestoreException("Population too high",
                        FirebaseFirestoreException.Code.ABORTED);
            }
        }
    }).addOnSuccessListener(new OnSuccessListener<Double>() {
        @Override
        public void onSuccess(Double result) {
            Log.d(TAG, "Transaction success: " + result);
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Transaction failure.", e);
        }
    });
    // [END transaction_with_result]
}
 
Example #23
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)));
}
 
Example #24
Source File: DocumentLiveData.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(DocumentSnapshot snapshot, FirebaseFirestoreException e) {
    if (e != null) {
        setValue(new Resource<>(e));
        return;
    }
    setValue(new Resource<>(snapshot.toObject(type)));
}
 
Example #25
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 #26
Source File: SolutionAggregation.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
private Task<Void> addRating(final DocumentReference restaurantRef, final float rating) {
    // Create reference for new rating, for use inside the transaction
    final DocumentReference ratingRef = restaurantRef.collection("ratings").document();

    // In a transaction, add the new rating and update the aggregate totals
    return db.runTransaction(new Transaction.Function<Void>() {
        @Override
        public Void apply(Transaction transaction) throws FirebaseFirestoreException {
            Restaurant restaurant = transaction.get(restaurantRef).toObject(Restaurant.class);

            // Compute new number of ratings
            int newNumRatings = restaurant.numRatings + 1;

            // Compute new average rating
            double oldRatingTotal = restaurant.avgRating * restaurant.numRatings;
            double newAvgRating = (oldRatingTotal + rating) / newNumRatings;

            // Set new restaurant info
            restaurant.numRatings = newNumRatings;
            restaurant.avgRating = newAvgRating;

            // Update restaurant
            transaction.set(restaurantRef, restaurant);

            // Update rating
            Map<String, Object> data = new HashMap<>();
            data.put("rating", rating);
            transaction.set(ratingRef, data, SetOptions.merge());

            return null;
        }
    });
}
 
Example #27
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 #28
Source File: FirestoreDocumentOnSubscribe.java    From Track-My-Location with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
    if (e != null) {
        emitter.onError(e);
    } else {
        if (documentSnapshot.exists()) {
            emitter.onNext(documentSnapshot);
        } else {
            emitter.onError(new DocumentNotExistsException());
        }
    }
}
 
Example #29
Source File: TransactionRunner.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private static boolean isRetryableTransactionError(Exception e) {
  if (e instanceof FirebaseFirestoreException) {
    // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
    // non-matching document versions with ABORTED. These errors should be retried.
    FirebaseFirestoreException.Code code = ((FirebaseFirestoreException) e).getCode();
    return code == FirebaseFirestoreException.Code.ABORTED
        || code == FirebaseFirestoreException.Code.FAILED_PRECONDITION
        || !Datastore.isPermanentError(((FirebaseFirestoreException) e).getCode());
  }
  return false;
}
 
Example #30
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private void failOutstandingPendingWritesAwaitingTasks() {
  for (Map.Entry<Integer, List<TaskCompletionSource<Void>>> entry :
      pendingWritesCallbacks.entrySet()) {
    for (TaskCompletionSource<Void> task : entry.getValue()) {
      task.setException(
          new FirebaseFirestoreException(
              "'waitForPendingWrites' task is cancelled due to User change.",
              FirebaseFirestoreException.Code.CANCELLED));
    }
  }

  pendingWritesCallbacks.clear();
}