com.google.firebase.firestore.DocumentReference Java Examples
The following examples show how to use
com.google.firebase.firestore.DocumentReference.
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 |
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: MapperTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@Test public void documentIdsRoundTrip() { // Implicitly verifies @DocumentId is ignored during serialization. DocumentReference ref = TestUtil.documentReference("coll/doc123"); assertEquals( Collections.emptyMap(), serialize(deserialize("{}", DocumentIdOnStringField.class, ref))); assertEquals( Collections.singletonMap("anotherProperty", 100), serialize( deserialize("{'anotherProperty': 100}", DocumentIdOnStringFieldAsProperty.class, ref))); assertEquals( Collections.emptyMap(), serialize(deserialize("{}", DocumentIdOnDocRefGetter.class, ref))); assertEquals( Collections.emptyMap(), serialize(deserialize("{}", DocumentIdOnInheritedDocRefSetter.class, ref))); assertEquals( Collections.singletonMap("nestedDocIdHolder", Collections.emptyMap()), serialize(deserialize("{'nestedDocIdHolder': {}}", DocumentIdOnNestedObjects.class, ref))); }
Example #3
Source File: DocSnippets.java From snippets-android with Apache License 2.0 | 6 votes |
public void writeBatch() { // [START write_batch] // Get a new write batch WriteBatch batch = db.batch(); // Set the value of 'NYC' DocumentReference nycRef = db.collection("cities").document("NYC"); batch.set(nycRef, new City()); // Update the population of 'SF' DocumentReference sfRef = db.collection("cities").document("SF"); batch.update(sfRef, "population", 1000000L); // Delete the city 'LA' DocumentReference laRef = db.collection("cities").document("LA"); batch.delete(laRef); // Commit the batch batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { // ... } }); // [END write_batch] }
Example #4
Source File: DocSnippets.java From snippets-android with Apache License 2.0 | 6 votes |
public void updateDocument() { // [START update_document] DocumentReference washingtonRef = db.collection("cities").document("DC"); // Set the "isCapital" field of the city 'DC' washingtonRef .update("capital", true) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "DocumentSnapshot successfully updated!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error updating document", e); } }); // [END update_document] }
Example #5
Source File: DocSnippets.java From snippets-android with Apache License 2.0 | 6 votes |
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 #6
Source File: MapperTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@Test public void documentIdsDeserializeConflictThrows() { final String expectedErrorMessage = "cannot apply @DocumentId on this property"; DocumentReference ref = TestUtil.documentReference("coll/doc123"); assertExceptionContains( expectedErrorMessage, () -> deserialize("{'docId': 'toBeOverwritten'}", DocumentIdOnStringField.class, ref)); assertExceptionContains( expectedErrorMessage, () -> deserialize( "{'docIdProperty': 'toBeOverwritten', 'anotherProperty': 100}", DocumentIdOnStringFieldAsProperty.class, ref)); assertExceptionContains( expectedErrorMessage, () -> deserialize( "{'nestedDocIdHolder': {'docId': 'toBeOverwritten'}}", DocumentIdOnNestedObjects.class, ref)); }
Example #7
Source File: DocSnippets.java From snippets-android with Apache License 2.0 | 6 votes |
public void addAlanTuring() { // [START add_alan_turing] // Create a new user with a first, middle, and last name Map<String, Object> user = new HashMap<>(); user.put("first", "Alan"); user.put("middle", "Mathison"); user.put("last", "Turing"); user.put("born", 1912); // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } }); // [END add_alan_turing] }
Example #8
Source File: DocSnippets.java From snippets-android with Apache License 2.0 | 6 votes |
public void addAdaLovelace() { // [START add_ada_lovelace] // Create a new user with a first and last name Map<String, Object> user = new HashMap<>(); user.put("first", "Ada"); user.put("last", "Lovelace"); user.put("born", 1815); // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } }); // [END add_ada_lovelace] }
Example #9
Source File: FirestoreRepositoryImpl.java From openwebnet-android with MIT License | 6 votes |
@Override public Observable<Void> deleteProfile(String userId, DocumentReference profileRef) { return getProfiles(userId) .flatMap(userProfiles -> { log.info("delete user profile: userId={} profileRef={}", userId, profileRef.getPath()); List<UserProfileModel> updatedUserProfiles = Stream .of(userProfiles) .map(userProfile -> { // update status if (userProfile.getProfileRef().getPath().equals(profileRef.getPath())) { return UserProfileModel .getBuilder(userProfile.toMap()) .status(UserProfileModel.Status.DELETED) .modifiedAt(new Date()) .build(); } return userProfile; }) .toList(); return updateUserProfile(userId, updatedUserProfiles); }); }
Example #10
Source File: SolutionCounters.java From snippets-android with Apache License 2.0 | 6 votes |
public Task<Void> createCounter(final DocumentReference ref, final int numShards) { // Initialize the counter document, then initialize each shard. return ref.set(new Counter(numShards)) .continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(@NonNull Task<Void> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } List<Task<Void>> tasks = new ArrayList<>(); // Initialize each shard with count=0 for (int i = 0; i < numShards; i++) { Task<Void> makeShard = ref.collection("shards") .document(String.valueOf(i)) .set(new Shard(0)); tasks.add(makeShard); } return Tasks.whenAll(tasks); } }); }
Example #11
Source File: DriverMapPresenter.java From ridesharing-android with MIT License | 6 votes |
public void startRide() { if (mState.getOrder() != null) { mView.showProgressBar(); DocumentReference washingtonRef = db.collection("orders").document(mState.getOrder().id); washingtonRef .update("status", Order.STARTED_RIDE) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mView.hideProgressBar(); Log.d(TAG, "DocumentSnapshot successfully updated!"); trackingPresenter.adjustTrackingState(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mView.hideProgressBar(); Log.w(TAG, "Error updating document", e); } }); } }
Example #12
Source File: FirestoreTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@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 #13
Source File: FirestoreRepositoryImpl.java From openwebnet-android with MIT License | 6 votes |
@Override public Observable<Void> renameProfile(String userId, DocumentReference profileRef, String name) { return getProfiles(userId) .flatMap(userProfiles -> { log.info("rename user profile: userId={} profileRef={} name={}", userId, profileRef.getPath(), name); List<UserProfileModel> updatedUserProfiles = Stream .of(userProfiles) .map(userProfile -> { // update name if (userProfile.getProfileRef().getPath().equals(profileRef.getPath())) { return UserProfileModel .getBuilder(userProfile.toMap()) .name(name) .modifiedAt(new Date()) .build(); } return userProfile; }) .toList(); return updateUserProfile(userId, updatedUserProfiles); }); }
Example #14
Source File: DriverMapPresenter.java From ridesharing-android with MIT License | 6 votes |
public void endRide() { if (mState.getOrder() != null) { mView.showProgressBar(); DocumentReference washingtonRef = db.collection("orders").document(mState.getOrder().id); washingtonRef .update("status", Order.COMPLETED) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mView.hideProgressBar(); Log.d(TAG, "DocumentSnapshot successfully updated!"); trackingPresenter.adjustTrackingState(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mView.hideProgressBar(); Log.w(TAG, "Error updating document", e); } }); } }
Example #15
Source File: DeviceLocationDataStore.java From Track-My-Location with GNU General Public License v3.0 | 5 votes |
public Observable<SharedLocation> getSharedLocationUpdate(String devId) { DocumentReference docRef = FirebaseFirestore.getInstance() .collection("shared_locations") .document(devId); return RxFirestore.getDocument(docRef) .map(documentSnapshot -> documentSnapshot.toObject(SharedLocation.class)); }
Example #16
Source File: CustomClassMapper.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
private void ensureValidDocumentIdType(String fieldDescription, String operation, Type type) { if (type != String.class && type != DocumentReference.class) { throw new IllegalArgumentException( fieldDescription + " is annotated with @DocumentId but " + operation + " " + type + " instead of String or DocumentReference."); } }
Example #17
Source File: UserProfileModel.java From openwebnet-android with MIT License | 5 votes |
private Builder(Map<String, Object> map) { this.profileRef = (DocumentReference) map.get(FIELD_PROFILE_REF); this.version = toInt(map.get(FIELD_VERSION)); this.name = (String) map.get(FIELD_NAME); this.createdAt = toDate(map.get(FIELD_CREATED_AT)); this.modifiedAt = toDate(map.get(FIELD_MODIFIED_AT)); this.status = Status.valueOf((String) map.get(FIELD_STATUS)); this.sharedFrom = (String) map.get(FIELD_SHARED_FROM); this.sharedTo = (List<String>) map.get(FIELD_SHARED_TO); }
Example #18
Source File: DocSnippets.java From snippets-android with Apache License 2.0 | 5 votes |
public void updateDocumentArray() { // [START update_document_array] DocumentReference washingtonRef = db.collection("cities").document("DC"); // Atomically add a new region to the "regions" array field. washingtonRef.update("regions", FieldValue.arrayUnion("greater_virginia")); // Atomically remove a region from the "regions" array field. washingtonRef.update("regions", FieldValue.arrayRemove("east_coast")); // [END update_document_array] }
Example #19
Source File: CustomClassMapper.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private static <T> T deserializeToClass(Object o, Class<T> clazz, DeserializeContext context) { if (o == null) { return null; } else if (clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)) { return deserializeToPrimitive(o, clazz, context); } else if (String.class.isAssignableFrom(clazz)) { return (T) convertString(o, context); } else if (Date.class.isAssignableFrom(clazz)) { return (T) convertDate(o, context); } else if (Timestamp.class.isAssignableFrom(clazz)) { return (T) convertTimestamp(o, context); } else if (Blob.class.isAssignableFrom(clazz)) { return (T) convertBlob(o, context); } else if (GeoPoint.class.isAssignableFrom(clazz)) { return (T) convertGeoPoint(o, context); } else if (DocumentReference.class.isAssignableFrom(clazz)) { return (T) convertDocumentReference(o, context); } else if (clazz.isArray()) { throw deserializeError( context.errorPath, "Converting to Arrays is not supported, please use Lists instead"); } else if (clazz.getTypeParameters().length > 0) { throw deserializeError( context.errorPath, "Class " + clazz.getName() + " has generic type parameters, please use GenericTypeIndicator instead"); } else if (clazz.equals(Object.class)) { return (T) o; } else if (clazz.isEnum()) { return deserializeToEnum(o, clazz, context); } else { return convertBean(o, clazz, context); } }
Example #20
Source File: CustomClassMapper.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
private static DocumentReference convertDocumentReference(Object o, DeserializeContext context) { if (o instanceof DocumentReference) { return (DocumentReference) o; } else { throw deserializeError( context.errorPath, "Failed to convert value of type " + o.getClass().getName() + " to DocumentReference"); } }
Example #21
Source File: SolutionAggregation.java From snippets-android with Apache License 2.0 | 5 votes |
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 #22
Source File: DocSnippets.java From snippets-android with Apache License 2.0 | 5 votes |
public void newDocument() { // [START new_document] Map<String, Object> data = new HashMap<>(); DocumentReference newCityRef = db.collection("cities").document(); // Later... newCityRef.set(data); // [END new_document] }
Example #23
Source File: ProfileActivity.java From openwebnet-android with MIT License | 5 votes |
private void shareProfile(DocumentReference profileRef, String emailPrefix) { String email = String.format("%s%s", emailPrefix, utilityService.getString(R.string.dialog_profile_share_email_suffix)); requestAction(() -> firebaseService.shareProfile(profileRef, email) .flatMap(profileId -> firebaseService.getProfiles()), profiles -> { log.info("shareProfile succeeded: refreshing"); updateProfiles(profiles); }); }
Example #24
Source File: DocSnippets.java From snippets-android with Apache License 2.0 | 5 votes |
public void subcollectionReference() { // [START subcollection_reference] DocumentReference messageRef = db .collection("rooms").document("roomA") .collection("messages").document("message1"); // [END subcollection_reference] }
Example #25
Source File: ProfileRepository.java From triviums with MIT License | 5 votes |
/** * Update profile in the database * @param name * @param photoUri */ public void updateProfile(String name, String photoUri) { DocumentReference docRef = firestore.collection("users") .document(userProfile.getUserUid()); docRef.update( "name", name, "profilePicture", photoUri) .addOnSuccessListener(aVoid -> {}) .addOnFailureListener(e -> { }); }
Example #26
Source File: SolutionCounters.java From snippets-android with Apache License 2.0 | 5 votes |
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 #27
Source File: DriverMapPresenter.java From ridesharing-android with MIT License | 5 votes |
public void acceptRide() { if (mState.selectedOrder != null) { mView.showProgressBar(); ObjectMapper mapper = new ObjectMapper(); DocumentReference washingtonRef = db.collection("orders").document(mState.selectedOrder.id); washingtonRef .update( "status", Order.ACCEPTED, "driver", mapper.convertValue(mState.getUser(), Map.class) ) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mView.hideProgressBar(); if (newOrderListenerRegistration != null) { newOrderListenerRegistration.remove(); } mState.newOrders.remove(mState.selectedOrder.id); mState.selectedOrder.marker.remove(); mState.updateOrder(mState.selectedOrder); subscribeOrderUpdates(); Log.d(TAG, "DocumentSnapshot successfully updated!"); trackingPresenter.adjustTrackingState(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mView.hideProgressBar(); Log.w(TAG, "Error updating document", e); } }); } }
Example #28
Source File: MapPresenter.java From ridesharing-android with MIT License | 5 votes |
public void cancelOrder() { if (orderListenerRegistration != null) { orderListenerRegistration.remove(); } if (mState.getOrder() != null) { mView.showProgressBar(); DocumentReference washingtonRef = db.collection("orders").document(mState.getOrder().id); washingtonRef .update( "status", Order.CANCELLED ) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mView.hideProgressBar(); if (mState.getOrder() != null && mState.getOrder().marker != null) { mState.getOrder().marker.remove(); } mState.updateOrder(null); mView.dismissOrderInfo(); mView.dismissTripEndInfo(); onOrderChanged(); Log.d(TAG, "DocumentSnapshot successfully updated!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mView.hideProgressBar(); Log.w(TAG, "Error updating document", e); } }); } }
Example #29
Source File: MainRepository.java From firestore-android-arch-components with Apache License 2.0 | 5 votes |
public void addRestaurants(final Context context) { // Add a bunch of random restaurants WriteBatch batch = firestore.batch(); for (int i = 0; i < 10; i++) { DocumentReference restRef = firestore.collection("restaurants").document(); // Create random restaurant / ratings Restaurant randomRestaurant = RestaurantUtil.getRandom(context); List<Rating> randomRatings = RatingUtil.getRandomList(randomRestaurant.numRatings); randomRestaurant.avgRating = RatingUtil.getAverageRating(randomRatings); // Add restaurant batch.set(restRef, randomRestaurant); // Add ratings to sub-collection for (Rating rating : randomRatings) { batch.set(restRef.collection("ratings").document(), rating); } } batch.commit().addOnCompleteListener(task -> { if (task.isSuccessful()) { Timber.d("Write batch succeeded."); } else { Timber.w("write batch failed.", task.getException()); } }); }
Example #30
Source File: RestaurantRepository.java From firestore-android-arch-components with Apache License 2.0 | 5 votes |
public DocumentLiveData<Restaurant> restaurant(final String id) { if (id == null) { return null; } final DocumentReference restaurantRef = restaurants.document(id); DocumentLiveData<Restaurant> data = new DocumentLiveData<>(restaurantRef, Restaurant.class); restaurantRef.addSnapshotListener(data); return data; }