@Override public void performFirebaseRegistration(Activity activity, final String email, String password) { FirebaseAuth.getInstance() .createUserWithEmailAndPassword(email, password) .addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.e(TAG, "performFirebaseRegistration:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { mOnRegistrationListener.onFailure(task.getException().getMessage()); } else { // Add the user to users table. /*DatabaseReference database= FirebaseDatabase.getInstance().getReference(); User user = new User(task.getResult().getUser().getUid(), email); database.child("users").push().setValue(user);*/ mOnRegistrationListener.onSuccess(task.getResult().getUser()); } } }); }
@Override public void onComplete(@NonNull Task<Void> task) { if (isDisposed()) return; if (!task.isSuccessful()) { Exception exception = task.getException(); if (terminated) { RxJavaPlugins.onError(exception); } else { try { terminated = true; observer.onError(exception); } catch (Throwable t) { Exceptions.throwIfFatal(t); RxJavaPlugins.onError(new CompositeException(task.getException(), t)); } } } }
@Override public final void signIn(final String email, final String password, final Callback callback) { signInCallback = callback; // TODO: 23-Feb-17 validate email, pass; firebaseAuthManager.signInWithEmailAndPassword(email, password, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { final Exception exception = task.getException(); printStackTrace(exception); if (signInCallback != null) { signInCallback.onComplete(task.isSuccessful(), exception != null ? exception.getMessage() : ""); } } }); }
@Override public void subscribe(final CompletableEmitter emitter) throws Exception { final OnCompleteListener<Void> listener = new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (!emitter.isDisposed()) { if (!task.isSuccessful()) { emitter.onError(task.getException()); } else { emitter.onComplete(); } } } }; reference.set(value).addOnCompleteListener(listener); }
private void LoginAnonymously() { mAuth.signInAnonymously() .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Log.w(TAG, "signInAnonymously", task.getException()); Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // ... } }); }
/** * Authenticate Google user with Firebase * @param acct Google account */ private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(mContext, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); onSuccess(); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.getException()); onFailed(); } } }); }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); FirebaseApp.initializeApp(this); FirebaseAuth.getInstance().addAuthStateListener(this); FirebaseAuth.getInstance().signInAnonymously() .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Log.w(TAG, "signInAnonymously", task.getException()); Toast.makeText(TestActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); }
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mFirebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(SignInActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } else { startActivity(new Intent(SignInActivity.this, MainActivity.class)); finish(); } } }); }
private void handleSignInResult(Task<GoogleSignInAccount> completedTask){ try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); // Signed in successfully, show authenticated UI. updateUI(account); googleSignInAccount = account; mAuthorizedAccount = account.getAccount(); GetListOfBlogTask task = new GetListOfBlogTask(mAuthorizedAccount); task.execute(); } catch (ApiException e) { // The ApiException status code indicates the detailed failure reason. // Please refer to the GoogleSignInStatusCodes class reference for more information. Tools.loge("signInResult:failed code=" + e.getStatusCode()); updateUI(null); } }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (fullScreenChatWindow != null) fullScreenChatWindow.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { // The Task returned from this call is always completed, no need to attach // a listener. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); handleSignInResult(task); } else { Log.w("Chat", "Received unknown code " + requestCode); } }
/** * Deletes many document matching a query specifier. * * @param query The query specifier. * @return A task that can be resolved upon completion of the request. */ public Task<Document> deleteMany(final Document query) { final Document doc = new Document(Parameters.QUERY, query); doc.put(Parameters.DATABASE, _database._dbName); doc.put(Parameters.COLLECTION, _collName); doc.put(Parameters.SINGLE_DOCUMENT, false); return _database._client._stitchClient.executeServiceFunction( "deleteMany", _database._client._service, doc ).continueWith(new Continuation<Object, Document>() { @Override public Document then(@NonNull Task<Object> task) throws Exception { if (task.isSuccessful()) { return (Document) task.getResult(); } else { Log.e(TAG, "Error while executing function", task.getException()); throw task.getException(); } } }); }
@Override public void onComplete(@NonNull Task<AuthResult> task) { int messageId = R.string.user_not_registered; if (task.isSuccessful()) { FirebaseAuth firebaseAuth = SessionManager.getFirebaseAuth(); FirebaseUser currentUser = firebaseAuth.getCurrentUser(); if (currentUser != null) { currentUser.sendEmailVerification(); DbService dbService = SessionManager.getDbService(); dbService.createOrUpdateUserAccountInFirebase(userRegistrationTO); messageId = R.string.verification_email_sent; } Intent intent = new Intent(context, LogInActivity.class); context.startActivity(intent); } Toast.makeText(context, messageId, Toast.LENGTH_SHORT).show(); }
public void insertAuthor(Author author) { mAuthorReference.child(author.getKey()).setValue(author).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d(LOG_TAG, e.getLocalizedMessage()); } }).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { insertAuthorCount++; if(insertAuthorCount== ITERATIONS){ logEvent("Insert "+ ITERATIONS +" Authors", initialTimeAuthorCount, new Date()); } } }); mAuthorReference.push(); }
private void firebaseAuthWithGoogle(GoogleSignInAccount account) { Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId()); showProgressDialog(); AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); hideProgressDialog(); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(AuthActivity.this, R.string.auth_failed, Toast.LENGTH_SHORT).show(); } // ... } }); }
private void link() { if (phoneNumberCheck() == true) { mAuth.getCurrentUser().linkWithCredential(credent) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "linkWithCredential:success"); Toast.makeText(ChangePhoneNumberActivity.this, "변경되었습니다", Toast.LENGTH_SHORT).show(); IntentBack(); } else { Log.w(TAG, "linkWithCredential:failure", task.getException()); Toast.makeText(ChangePhoneNumberActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // ... } }); } else { Toast.makeText(ChangePhoneNumberActivity.this, "이미 등록되어있는 번호입니다.", Toast.LENGTH_SHORT).show(); } }
@Override public Promise<Void, BError, Void> sendPasswordResetMail(String email){ final Deferred<Void, BError, Void> deferred = new DeferredObject<>(); OnCompleteListener<Void> resultHandler = new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { if(DEBUG) Timber.v("Email sent"); deferred.resolve(null); } else { deferred.reject(getFirebaseError(DatabaseError.fromException(task.getException()))); } } }; FirebaseAuth.getInstance().sendPasswordResetEmail(email).addOnCompleteListener(resultHandler); return deferred.promise(); }
private void handleFacebookAccessToken(AccessToken token) { Log.e(TAG, "handleFacebookAccessToken:" + token); AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.e(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUser(user); updateUi(); } else { // If sign in fails, display a message to the user. Log.e(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(RegisterActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // ... } }); }
public void sendEmailVerification() { // [START send_email_verification] FirebaseAuth auth = FirebaseAuth.getInstance(); FirebaseUser user = auth.getCurrentUser(); user.sendEmailVerification() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); } } }); // [END send_email_verification] }
protected void insertPost(Post post) { mPostReference.child(post.getKey()).setValue(post).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d(LOG_TAG, e.getLocalizedMessage()); } }).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { insertPostCount++; if(insertPostCount== ITERATIONS){ logEvent("Insert "+ ITERATIONS +" Posts", initialTimePostCount, new Date()); updateData(); } } }); mPostReference.push(); }
private void handleTwitterSession(TwitterSession session) { Utils.d("Twitter:HandleSession:" + session); AuthCredential credential = TwitterAuthProvider.getCredential( session.getAuthToken().token, session.getAuthToken().secret); mAuth.signInWithCredential(credential) .addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Utils.d("signInWithCredential:success"); } else { // If sign in fails, display a message to the user. Utils.w("signInWithCredential:failure: " + task.getException()); } // ... } }); }
private void fetchRemoteConfigs () { Utils.d("Loading Remote Configs"); long cacheExpiration = 3600; if (mFirebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) { cacheExpiration = 0; } mFirebaseRemoteConfig.fetch(cacheExpiration) .addOnCompleteListener(activity, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Utils.d("RemoteConfig, Fetch Successed"); mFirebaseRemoteConfig.activateFetched(); } else { Utils.d("RemoteConfig, Fetch Failed"); } // Utils.d("Fetched Value: " + getValue("firebase_remoteconfig_test")); } }); }
/** * Start getting your location. * WARNING Don't forget to check on ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION before calling this function */ @SuppressWarnings("MissingPermission") public void getLastLocation(){ if(checkLocationPermissions()) { if(checkPlayServices()) { if(mListener != null) { mFusedLocationClient.getLastLocation().addOnCompleteListener(mActivity, new OnCompleteListener<Location>(){ @Override public void onComplete(@NonNull Task<Location> task){ if(task.isSuccessful() && task.getResult() != null) { Location lastLocation = task.getResult(); mListener.onLocationReady(lastLocation); } else{ mListener.onError("No location exists. Check if GPS enabled"); } } }); } else Log.w(TAG, "Location listener not attached"); } else Log.w(TAG, "Google play services not installed or not enabled. Or version older than needed"); } else Log.e(TAG, "You should grant ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION first"); }
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mFirebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(SignInActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } else { startActivity(new Intent(SignInActivity.this, MainActivity.class)); finish(); } } }); }
public void checkAccountEmailExistsInFirebase(final String email) { FirebaseApp.initializeApp(this); FirebaseAuth mAuth = FirebaseAuth.getInstance(); mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() { @Override public void onComplete(@NonNull Task<ProviderQueryResult> task) { if((task.getResult().getProviders() != null && task.getResult().getProviders().isEmpty())){ signUpUser(email); }else{ mProgressDialog.dismiss(); Snackbar.make(mConstraintLayout, "Account with Email Address Already Exists.", Snackbar.LENGTH_LONG ).show(); } } }); }
private void getAllUsers() { // [START get_all_users] db.collection("users") .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (DocumentSnapshot document : task.getResult()) { Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.w(TAG, "Error getting documents.", task.getException()); } } }); // [END get_all_users] }
/** * @return A task that can be resolved upon completion of registration to both GCM and Stitch. */ @Override public Task<Void> register() { final InstanceID instanceId = InstanceID.getInstance(getContext()); return getRegistrationToken(instanceId, _info.getSenderId()) .continueWithTask(new Continuation<String, Task<Void>>() { @Override public Task<Void> then(@NonNull final Task<String> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } return registerWithServer(task.getResult()); } }); }
private void getSignRequest() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) { Log.i(TAG, "getSignRequest permission is granted"); Task<SignRequestParams> getSignRequestTask = asyncGetSignRequest(); getSignRequestTask.addOnCompleteListener(new OnCompleteListener<SignRequestParams>() { @Override public void onComplete(@NonNull Task<SignRequestParams> task) { SignRequestParams signRequest = task.getResult(); if (signRequest == null) { Log.i(TAG, "signRequest is null"); return; } sendSignRequestToClient(signRequest); } }); } else { Log.i(TAG, "getSignRequest permission is requested"); ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.GET_ACCOUNTS}, GET_ACCOUNTS_PERMISSIONS_REQUEST_SIGN); } }
private Task<Void> addRating(final DocumentReference restaurantRef, final Rating 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 restaurants.getFirestore().runTransaction(transaction -> { 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.rating) / newNumRatings; // Set new restaurant info restaurant.numRatings = newNumRatings; restaurant.avgRating = newAvgRating; // Commit to Firestore transaction.set(restaurantRef, restaurant); transaction.set(ratingRef, rating); return null; }); }
public void sendToAllReliably(final String messageString) { byte [] message = messageString.getBytes(); for (final String participantId : mRoom.getParticipantIds()) { if (!participantId.equals(mMyParticipantId)) { mRealTimeMultiplayerClient.sendReliableMessage(message, mRoom.getRoomId(), participantId, this).addOnCompleteListener( new OnCompleteListener<Integer>() { @Override public void onComplete(@NonNull Task<Integer> task) { // Keep track of which messages are sent, if desired. Log.d("MEXX", "Sent '" + messageString + "' to " + participantId); recordMessageToken(task.getResult()); } }); } } }
private void resetPassword() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Reset Password") .setMessage("Are you sure you want to reset your password ?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { FirebaseAuth.getInstance().sendPasswordResetEmail(userEmail) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); Toast.makeText(MapsActivity.this, "Email Sent to " + userEmail, Toast.LENGTH_SHORT).show(); } } }); } }) .setNegativeButton("No", null) .show(); }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e); // ... } } }
@Override public Completable deleteProfile(final String uid) { return Completable.create( new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); rootRef.child(USER_PROFILES) .child(uid) .setValue(null) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { e.onComplete(); } else { e.onError(task.getException()); } } }); } }); }
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // ... } }); }
public void signIn(String email, String password){ mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Log.w(TAG, "signInWithEmail:failed", task.getException()); progressBar.setVisibility(View.GONE); Toast.makeText(getApplicationContext(), R.string.auth_failed, Toast.LENGTH_SHORT).show(); setInputs(true); } // ... } }); }
/** * @param emit * @param <R> * @return */ @NonNull @CheckReturnValue public static <R> OnCompleteListener<R> listener(@NonNull final MaybeEmitter<R> emit) { return new OnCompleteListener<R>() { @Override public void onComplete(@NonNull final Task<R> task) { if (!emit.isDisposed()) { if (task.isSuccessful()) { R result = task.getResult(); if (result != null) { emit.onSuccess(result); } emit.onComplete(); } else { Exception e = task.getException(); emit.onError(e != null ? e : new RuntimeException()); } } } }; }
private void fetchFirebaseRemoteConfig() { long cacheExpiration = 36008*12; // 12 hour in seconds. mFirebaseRemoteConfig.fetch(cacheExpiration) .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { // After config data is successfully fetched, it must be activated before newly fetched // values are returned. mFirebaseRemoteConfig.activateFetched(); } /*else { Toast.makeText(MainActivity.this, "Fetch Failed", Toast.LENGTH_SHORT).show(); }*/ // comment it out to test getRemoteConfigs(); } }); }
private void updateDeleteField() { // [START update_delete_field] DocumentReference docRef = db.collection("cities").document("BJ"); // Remove the 'capital' field from the document Map<String,Object> updates = new HashMap<>(); updates.put("capital", FieldValue.delete()); docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() { // [START_EXCLUDE] @Override public void onComplete(@NonNull Task<Void> task) {} // [START_EXCLUDE] }); // [END update_delete_field] }
/** * Update last notification time * @param plantId - the id of the plant (species_name) * @param field - the field to update */ public void updateNotificationTime(final String plantId, final String field) { if (plantId != null) { getPlantReference(plantId).child(field).setValue(System.currentTimeMillis()).addOnCompleteListener(new OnCompleteListener<Void>() { /** * Update last fertilized time * * @param task - update task */ @Override public void onComplete(@NonNull Task<Void> task) { // nothing, yet } }); } }