com.google.firebase.firestore.DocumentSnapshot Java Examples

The following examples show how to use com.google.firebase.firestore.DocumentSnapshot. 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 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 #3
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 #4
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 #5
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 #6
Source File: ObservationConverter.java    From ground-android with Apache License 2.0 6 votes vote down vote up
static Observation toObservation(Feature feature, DocumentSnapshot snapshot)
    throws DataStoreException {
  ObservationDocument doc = snapshot.toObject(ObservationDocument.class);
  String featureId = checkNotNull(doc.getFeatureId(), "featureId");
  String featureTypeId = checkNotNull(doc.getFeatureTypeId(), "featureTypeId");
  String formId = checkNotNull(doc.getFormId(), "formId");
  if (!feature.getId().equals(featureId)) {
    Log.w(TAG, "Observation featureId doesn't match specified feature id");
  }
  if (!feature.getLayer().getId().equals(featureTypeId)) {
    Log.w(TAG, "Observation layerId doesn't match specified feature's layerId");
  }
  Form form = checkNotEmpty(feature.getLayer().getForm(formId), "form");
  AuditInfoNestedObject created = checkNotNull(doc.getCreated(), "created");
  AuditInfoNestedObject modified = Optional.ofNullable(doc.getModified()).orElse(created);
  return Observation.newBuilder()
      .setId(snapshot.getId())
      .setProject(feature.getProject())
      .setFeature(feature)
      .setForm(form)
      .setResponses(toResponseMap(doc.getResponses()))
      .setCreated(AuditInfoConverter.toAuditInfo(created))
      .setLastModified(AuditInfoConverter.toAuditInfo(modified))
      .build();
}
 
Example #7
Source File: FirestoreRecyclerAdapter.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void onChildChanged(@NonNull ChangeEventType type,
                           @NonNull DocumentSnapshot snapshot,
                           int newIndex,
                           int oldIndex) {
    switch (type) {
        case ADDED:
            notifyItemInserted(newIndex);
            break;
        case CHANGED:
            notifyItemChanged(newIndex);
            break;
        case REMOVED:
            notifyItemRemoved(oldIndex);
            break;
        case MOVED:
            notifyItemMoved(oldIndex, newIndex);
            break;
        default:
            throw new IllegalStateException("Incomplete case statement");
    }
}
 
Example #8
Source File: FeatureConverter.java    From ground-android with Apache License 2.0 6 votes vote down vote up
static Feature toFeature(@NonNull Project project, @NonNull DocumentSnapshot doc)
    throws DataStoreException {
  FeatureDocument f = checkNotNull(doc.toObject(FeatureDocument.class), "feature data");
  String featureTypeId = checkNotNull(f.getFeatureTypeId(), "featureTypeId");
  Layer layer = checkNotEmpty(project.getLayer(featureTypeId), "layer " + f.getFeatureTypeId());
  // TODO: Rename "point" and "center" to "location" throughout for clarity.
  GeoPoint geoPoint = checkNotNull(f.getCenter(), "center");
  Point location =
      Point.newBuilder()
          .setLatitude(geoPoint.getLatitude())
          .setLongitude(geoPoint.getLongitude())
          .build();
  AuditInfoNestedObject created = checkNotNull(f.getCreated(), "created");
  AuditInfoNestedObject modified = Optional.ofNullable(f.getModified()).orElse(created);
  return Feature.newBuilder()
      .setId(doc.getId())
      .setProject(project)
      .setCustomId(f.getCustomId())
      .setCaption(f.getCaption())
      .setLayer(layer)
      .setPoint(location)
      .setCreated(AuditInfoConverter.toAuditInfo(created))
      .setLastModified(AuditInfoConverter.toAuditInfo(modified))
      .build();
}
 
Example #9
Source File: QuerySnapshotConverter.java    From ground-android with Apache License 2.0 6 votes vote down vote up
private static <T> RemoteDataEvent<T> toEvent(
    DocumentChange dc, Function<DocumentSnapshot, T> converter) {
  try {
    Log.v(TAG, dc.getDocument().getReference().getPath() + " " + dc.getType());
    String id = dc.getDocument().getId();
    switch (dc.getType()) {
      case ADDED:
        return RemoteDataEvent.loaded(id, converter.apply(dc.getDocument()));
      case MODIFIED:
        return RemoteDataEvent.modified(id, converter.apply(dc.getDocument()));
      case REMOVED:
        return RemoteDataEvent.removed(id);
      default:
        return RemoteDataEvent.error(
            new DataStoreException("Unknown DocumentChange type: " + dc.getType()));
    }
  } catch (DataStoreException e) {
    return RemoteDataEvent.error(e);
  }
}
 
Example #10
Source File: FirestoreDataSource.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
private PageKey getNextPageKey(@NonNull QuerySnapshot snapshot) {
    List<DocumentSnapshot> data = snapshot.getDocuments();
    DocumentSnapshot last = getLast(data);

    return new PageKey(last, null);
}
 
Example #11
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 #12
Source File: RestaurantAdapter.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
public void bind(final DocumentSnapshot snapshot,
                 final OnRestaurantSelectedListener listener) {

    Restaurant restaurant = snapshot.toObject(Restaurant.class);
    Resources resources = itemView.getResources();

    // Load image
    Glide.with(binding.restaurantItemImage.getContext())
            .load(restaurant.getPhoto())
            .into(binding.restaurantItemImage);

    binding.restaurantItemName.setText(restaurant.getName());
    binding.restaurantItemRating.setRating((float) restaurant.getAvgRating());
    binding.restaurantItemCity.setText(restaurant.getCity());
    binding.restaurantItemCategory.setText(restaurant.getCategory());
    binding.restaurantItemNumRatings.setText(resources.getString(R.string.fmt_num_ratings,
            restaurant.getNumRatings()));
    binding.restaurantItemPrice.setText(RestaurantUtil.getPriceString(restaurant));

    // Click listener
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (listener != null) {
                listener.onRestaurantSelected(snapshot);
            }
        }
    });
}
 
Example #13
Source File: FirestoreDataSource.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
private Runnable getRetryLoadAfter(@NonNull final LoadParams<PageKey> params,
                                   @NonNull final LoadCallback<PageKey, DocumentSnapshot> callback) {
    return new Runnable() {
        @Override
        public void run() {
            loadAfter(params, callback);
        }
    };
}
 
Example #14
Source File: FirestoreDataSource.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Nullable
private DocumentSnapshot getLast(@NonNull List<DocumentSnapshot> data) {
    if (data.isEmpty()) {
        return null;
    } else {
        return data.get(data.size() - 1);
    }
}
 
Example #15
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 #16
Source File: FirestoreDataSource.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void loadBefore(@NonNull LoadParams<PageKey> params,
                       @NonNull LoadCallback<PageKey, DocumentSnapshot> callback) {
    // Ignored for now, since we only ever append to the initial load.
    // Future work:
    //  * Could we dynamically unload past pages?
    //  * Could we ask the developer for both a forward and reverse base query
    //    so that we can load backwards easily?
}
 
Example #17
Source File: FirestoreArrayTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onChildChanged(@NonNull ChangeEventType type,
                           @NonNull DocumentSnapshot snapshot,
                           int newIndex,
                           int oldIndex) {
    Log.d(TAG, "onChildChanged: " + type + " at index " + newIndex);
}
 
Example #18
Source File: RestaurantDetailActivity.java    From quickstart-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: ProfileFragment.java    From triviums with MIT License 5 votes vote down vote up
public void getAchievementData() {
    viewModel.getLiveData().observe(getViewLifecycleOwner(), data -> {
        binding.progressBar.setVisibility(View.GONE);
        binding.loadingTxt.setVisibility(View.GONE);
        if (data != null) {
            for (DocumentSnapshot document : data) {
                values.add(Integer.valueOf(String.valueOf(document.getData().get("score"))));
            }

            for (Integer score : values) {
                totalScore += score;
            }

            if (totalScore > 0) {
                //Check if user has played any quiz
                binding.message.setVisibility(View.GONE);
                binding.achievements.setVisibility(View.VISIBLE);
            } else {
                //Check if user has played any quiz
                binding.message.setVisibility(View.VISIBLE);
                binding.achievements.setVisibility(View.GONE);
            }
            adapter.updateData(data);

            if (totalScore <= 1) {
                binding.totalXp.setText(String.format(getString(R.string.point), totalScore));
            } else {
                binding.totalXp.setText(String.format(getString(R.string.points), totalScore));
            }

        }
    });
}
 
Example #21
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 #22
Source File: RestaurantAdapter.java    From friendlyeats-android with Apache License 2.0 5 votes vote down vote up
public void bind(final DocumentSnapshot snapshot,
                 final OnRestaurantSelectedListener listener) {

    Restaurant restaurant = snapshot.toObject(Restaurant.class);
    Resources resources = itemView.getResources();

    // Load image
    Glide.with(imageView.getContext())
            .load(restaurant.getPhoto())
            .into(imageView);

    nameView.setText(restaurant.getName());
    ratingBar.setRating((float) restaurant.getAvgRating());
    cityView.setText(restaurant.getCity());
    categoryView.setText(restaurant.getCategory());
    numRatingsView.setText(resources.getString(R.string.fmt_num_ratings,
            restaurant.getNumRatings()));
    priceView.setText(RestaurantUtil.getPriceString(restaurant));

    // Click listener
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (listener != null) {
                listener.onRestaurantSelected(snapshot);
            }
        }
    });
}
 
Example #23
Source File: MainActivity.java    From friendlyeats-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onRestaurantSelected(DocumentSnapshot restaurant) {
    // Go to the details page for the selected restaurant
    Intent intent = new Intent(this, RestaurantDetailActivity.class);
    intent.putExtra(RestaurantDetailActivity.KEY_RESTAURANT_ID, restaurant.getId());

    startActivity(intent);
}
 
Example #24
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 #25
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 #26
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 #27
Source File: RestaurantUtil.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
/**
 * Delete all documents in a collection. Uses an Executor to perform work on a background
 * thread. This does *not* automatically discover and delete subcollections.
 */
private static Task<Void> deleteCollection(final CollectionReference collection,
                                           final int batchSize,
                                           Executor executor) {

    // Perform the delete operation on the provided Executor, which allows us to use
    // simpler synchronous logic without blocking the main thread.
    return Tasks.call(executor, () -> {
        // Get the first batch of documents in the collection
        Query query = collection.orderBy("__name__").limit(batchSize);

        // Get a list of deleted documents
        List<DocumentSnapshot> deleted = deleteQueryBatch(query);

        // While the deleted documents in the last batch indicate that there
        // may still be more documents in the collection, page down to the
        // next batch and delete again
        while (deleted.size() >= batchSize) {
            // Move the query cursor to start after the last doc in the batch
            DocumentSnapshot last = deleted.get(deleted.size() - 1);
            query = collection.orderBy("__name__")
                    .startAfter(last.getId())
                    .limit(batchSize);

            deleted = deleteQueryBatch(query);
        }

        return null;
    });

}
 
Example #28
Source File: OrderParser.java    From ridesharing-android with MIT License 5 votes vote down vote up
@Nullable
@Override
public Order parse(DocumentSnapshot doc) {
    if (doc.getData() != null) {
        Order order = mapper.convertValue(doc.getData(), Order.class);
        order.id = doc.getId();
        return order;
    }
    return null;
}
 
Example #29
Source File: UserParser.java    From ridesharing-android with MIT License 5 votes vote down vote up
@Nullable
@Override
public User parse(DocumentSnapshot doc) {
    if (doc.getData() != null) {
        User user = mapper.convertValue(doc.getData(), User.class);
        user.id = doc.getId();
        return user;
    }
    return null;
}
 
Example #30
Source File: FirestoreDataSource.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
private Runnable getRetryLoadInitial(@NonNull final LoadInitialParams<PageKey> params,
                                     @NonNull final LoadInitialCallback<PageKey, DocumentSnapshot> callback) {
    return new Runnable() {
        @Override
        public void run() {
            loadInitial(params, callback);
        }
    };
}