com.google.android.gms.tasks.OnSuccessListener Java Examples

The following examples show how to use com.google.android.gms.tasks.OnSuccessListener. 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: Manager.java    From react-native-fitness with MIT License 9 votes vote down vote up
public void subscribeToSteps(Context context, final Promise promise){
    final GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(context);
    if(account == null){
        promise.resolve(false);
        return;
    }
    Fitness.getRecordingClient(context, account)
            .subscribe(DataType.TYPE_STEP_COUNT_DELTA)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    promise.resolve(true);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    promise.resolve(false);
                }
            });
}
 
Example #2
Source File: MainActivity.java    From Beauty-Compass with Apache License 2.0 7 votes vote down vote up
/**
 *
 */
private void initialize() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    FusedLocationProviderClient fusedLocationProviderClient = new FusedLocationProviderClient(getApplicationContext());
    fusedLocationProviderClient.getLastLocation()
            .addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        updateDayState(location);
                        mPositionTextView.setVisibility(View.VISIBLE);
                        mPositionTextView.setText(AppUtils.convert(location.getLatitude(), location.getLongitude()));
                    }
                }
            });
}
 
Example #3
Source File: MainActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
private void onSmokeTestClicked() {
    FirebaseAuth.getInstance()
            .signInAnonymously()
            .addOnSuccessListener(this, new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult authResult) {
                    Log.d(TAG, "auth:onSuccess");

                    // Run snippets
                    DocSnippets docSnippets = new DocSnippets(mFirestore);
                    docSnippets.runAll();
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d(TAG, "auth:onFailure", e);
                }
            });
}
 
Example #4
Source File: ViewModels.java    From firebase_mlkit_language with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void handleEvent(final MethodChannel.Result result) {
    FirebaseTranslateModelManager.getInstance().getAvailableModels(FirebaseApp.getInstance())
            .addOnSuccessListener(new OnSuccessListener<Set<FirebaseTranslateRemoteModel>>() {
                @Override
                public void onSuccess(Set<FirebaseTranslateRemoteModel> models) {
                    List<Map<String, Object>> translateModels = new ArrayList<>(models.size());
                    for (FirebaseTranslateRemoteModel model : models) {
                        Map<String, Object> langData = new HashMap<>();
                        langData.put("languageCode", model.getLanguageCode());
                        translateModels.add(langData);
                    }
                    result.success(translateModels);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    result.error("viewError", e.getLocalizedMessage(), null);
                }
            });
}
 
Example #5
Source File: MainActivity.java    From android-play-awareness with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to retrieve weather data using the Snapshot API.  Since Weather is protected
 * by a runtime permission, this snapshot code is going to be called in multiple places:
 * {@link #printSnapshot()} when the permission has already been accepted, and
 * {@link #onRequestPermissionsResult(int, String[], int[])} when the permission is requested
 * and has been granted.
 */
private void getWeatherSnapshot() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        Awareness.getSnapshotClient(this).getWeather()
                .addOnSuccessListener(new OnSuccessListener<WeatherResponse>() {
                    @Override
                    public void onSuccess(WeatherResponse weatherResponse) {
                        Weather weather = weatherResponse.getWeather();
                        weather.getConditions();
                        mLogFragment.getLogView().println("Weather: " + weather);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "Could not get weather: " + e);
                    }
                });
    }
}
 
Example #6
Source File: AndroidLocationProvider.java    From BLE-Indoor-Positioning with Apache License 2.0 6 votes vote down vote up
@SuppressLint("MissingPermission")
public static void requestLastKnownLocation() {
    final AndroidLocationProvider instance = getInstance();
    if (!instance.hasLocationPermission()) {
        return;
    }
    Log.d(TAG, "Requesting last known location");
    instance.fusedLocationClient.getLastLocation()
            .addOnSuccessListener(getInstance().activity, new OnSuccessListener<android.location.Location>() {
                @Override
                public void onSuccess(android.location.Location androidLocation) {
                    if (androidLocation != null) {
                        instance.onLocationUpdateReceived(androidLocation);
                    } else {
                        Log.w(TAG, "Unable to get last known location");
                    }
                }
            });
}
 
Example #7
Source File: RecipeActivity.java    From search-samples with Apache License 2.0 6 votes vote down vote up
private void indexRecipe() {
    Indexable recipeToIndex = new Indexable.Builder()
            .setName(mRecipe.getTitle())
            .setUrl(mRecipe.getRecipeUrl())
            .setImage(mRecipe.getPhoto())
            .setDescription(mRecipe.getDescription())
            .build();

    Task<Void> task = FirebaseAppIndex.getInstance().update(recipeToIndex);
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "App Indexing API: Successfully added " + mRecipe.getTitle() + " to " +
                    "index");
        }
    });

    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.e(TAG, "App Indexing API: Failed to add " + mRecipe.getTitle() + " to index. " +
                    "" + exception.getMessage());
        }
    });
}
 
Example #8
Source File: FirebaseDatabaseHelper.java    From Duolingo-Clone with MIT License 6 votes vote down vote up
@Override
public void setUserInfo(UserData userData) {

    if (Injection.providesAuthHelper().getAuthInstance().getCurrentUser() != null) {

        String userID = Injection.providesAuthHelper().getAuthInstance().getCurrentUser().getUid();

        myRef.child("user")
                .child(userID)
                .child("user_data")
                .setValue(userData)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                        Log.d(TAG, "User's data has been updated");
                    }
                });
    }
}
 
Example #9
Source File: Fido2DemoActivity.java    From security-samples with Apache License 2.0 6 votes vote down vote up
private void sendSignRequestToClient(PublicKeyCredentialRequestOptions options) {
    Fido2ApiClient fido2ApiClient = Fido.getFido2ApiClient(this.getApplicationContext());

    Task<Fido2PendingIntent> result = fido2ApiClient.getSignIntent(options);

    result.addOnSuccessListener(
            new OnSuccessListener<Fido2PendingIntent>() {
                @Override
                public void onSuccess(Fido2PendingIntent fido2PendingIntent) {
                    if (fido2PendingIntent.hasPendingIntent()) {
                        try {
                            fido2PendingIntent.launchPendingIntent(Fido2DemoActivity.this, REQUEST_CODE_SIGN);
                        } catch (IntentSender.SendIntentException e) {
                            Log.e(TAG, "Error launching pending intent for sign request", e);
                        }
                    }
                }
            });
}
 
Example #10
Source File: MainActivity.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the asset that was created from the photo we took by adding it to the Data Item store.
 */
private void sendPhoto(Asset asset) {
    PutDataMapRequest dataMap = PutDataMapRequest.create(IMAGE_PATH);
    dataMap.getDataMap().putAsset(IMAGE_KEY, asset);
    dataMap.getDataMap().putLong("time", new Date().getTime());
    PutDataRequest request = dataMap.asPutDataRequest();
    request.setUrgent();

    Task<DataItem> dataItemTask = Wearable.getDataClient(this).putDataItem(request);

    dataItemTask.addOnSuccessListener(
            new OnSuccessListener<DataItem>() {
                @Override
                public void onSuccess(DataItem dataItem) {
                    LOGD(TAG, "Sending image was successful: " + dataItem);
                }
            });
}
 
Example #11
Source File: FirebaseImageLoader.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void loadData(@NonNull Priority priority,
                     @NonNull final DataCallback<? super InputStream> callback) {
    mStreamTask = mRef.getStream();
    mStreamTask
            .addOnSuccessListener(new OnSuccessListener<StreamDownloadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(StreamDownloadTask.TaskSnapshot snapshot) {
                    mInputStream = snapshot.getStream();
                    callback.onDataReady(mInputStream);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    callback.onLoadFailed(e);
                }
            });
}
 
Example #12
Source File: MainActivity.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onStop() {
    super.onStop();

    if (articleId == null) return;
    final Uri BASE_URL = Uri.parse("https://www.example.com/articles/");
    final String APP_URI = BASE_URL.buildUpon().appendPath(articleId).build().toString();

    Task<Void> actionTask = FirebaseUserActions.getInstance().end(Actions.newView(TITLE,
            APP_URI));

    actionTask.addOnSuccessListener(MainActivity.this, new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "App Indexing API: Successfully ended view action on " + TITLE);
        }
    });

    actionTask.addOnFailureListener(MainActivity.this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.e(TAG, "App Indexing API: Failed to end view action on " + TITLE + ". "
                    + exception.getMessage());
        }
    });
}
 
Example #13
Source File: detailActivity.java    From Doctorave with MIT License 6 votes vote down vote up
public void deleteFromFirebase(final String id){
    Query hekkQuery = mDatabaseReference;

    hekkQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            dataSnapshot.child(id).getRef().removeValue()
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            deletePhotoFromStorage(id);
                        }
                    });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

    /////this is for firebase storage
    Task<Void> task = mStorageReference.child(String.valueOf(id).concat("_Image")).delete();
}
 
Example #14
Source File: FeedBackActivity.java    From Google-Hosts with Apache License 2.0 6 votes vote down vote up
private void submitFeedbackData() {
    //记录当前时间
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
    String currentDate = dateFormat.format(new Date());
    //创建数据对象
    FeedbackInfo feedbackInfo = new FeedbackInfo(mContent.getEditText().getText().toString(),
            mAddress.getEditText().getText().toString());
    Log.i(TAG, "开始提交数据");
    //开始提交数据
    Task<Void> voidTask = myRef.child(currentDate).setValue(feedbackInfo);
    voidTask.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.i(TAG, "数据提交提交成功");
        }
    });
    //结束当前界面
    finish();
    //提示信息
    Toast.makeText(getApplicationContext(), "您的反馈已经提交\n感谢您的支持", Toast.LENGTH_LONG).show();
}
 
Example #15
Source File: SocialProviderResponseHandler.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private void handleGenericIdpLinkingFlow(@NonNull final IdpResponse idpResponse) {
    ProviderUtils.fetchSortedProviders(getAuth(), getArguments(), idpResponse.getEmail())
            .addOnSuccessListener(new OnSuccessListener<List<String>>() {
                @Override
                public void onSuccess(@NonNull List<String> providers) {
                    if (providers.isEmpty()) {
                        setResult(Resource.<IdpResponse>forFailure(
                                new FirebaseUiException(ErrorCodes.DEVELOPER_ERROR,
                                        "No supported providers.")));
                        return;
                    }
                    startWelcomeBackFlowForLinking(providers.get(0), idpResponse);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    setResult(Resource.<IdpResponse>forFailure(e));
                }
            });
}
 
Example #16
Source File: Request.java    From play_games with MIT License 6 votes vote down vote up
private OnSuccessListener<AnnotatedData<LeaderboardsClient.LeaderboardScores>> scoreSuccessHandler() {
    return new OnSuccessListener<AnnotatedData<LeaderboardsClient.LeaderboardScores>>() {
        @Override
        public void onSuccess(AnnotatedData<LeaderboardsClient.LeaderboardScores> data) {
            LeaderboardsClient.LeaderboardScores scores = data.get();
            Map<String, Object> successMap = new HashMap<>();
            successMap.put("type", "SUCCESS");
            successMap.put("leaderboardDisplayName", scores.getLeaderboard().getDisplayName());
            List<Map<String, Object>> list = new ArrayList<>();
            Iterator<LeaderboardScore> it = scores.getScores().iterator();
            while (it.hasNext()) {
                list.add(scoreToMap(it.next()));
            }
            successMap.put("scores", list);

            scores.release();
            result(successMap);
        }
    };
}
 
Example #17
Source File: NotificationActivity.java    From Hify with MIT License 6 votes vote down vote up
private void updateReadStatus() {

        String read=getIntent().getStringExtra("read");
        if(read.equals("false")){
            Map<String,Object> readMap=new HashMap<>();
            readMap.put("read","true");

            mFirestore.collection("Users").document(current_id).collection("Notifications")
                    .document(getIntent().getStringExtra("doc_id")).update(readMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.i("done","read:true");
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.i("error","read:false::"+e.getLocalizedMessage());
                }
            });
        }

    }
 
Example #18
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void getLastLocation() {
  FusedLocationProviderClient fusedLocationClient;
  fusedLocationClient =
    LocationServices.getFusedLocationProviderClient(this);
  if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION)
      == PERMISSION_GRANTED ||
      ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION)
      == PERMISSION_GRANTED) {
    fusedLocationClient.getLastLocation()
      .addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
          updateTextView(location);
        }
      });
  }
}
 
Example #19
Source File: LocationHelper.java    From Compass with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("MissingPermission")
public void onCreate() {
    DLog.d(TAG, "onCreate() called");
    if (permissionGranted()) {
        if (!Utility.isNetworkAvailable(mContext)) {
            return;
        }
        LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        mLocationListener = new LocationListener(mContext);
        mLocationListener.setLocationValueListener(mLocationValueListener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, mLocationListener);
        FusedLocationProviderClient client = getFusedLocationProviderClient(mContext);
        client.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                // Got last known location. In some rare situations this can be null.
                if (location != null) {
                    // Logic to handle location object
                    mLocationListener.onLocationChanged(location);
                }
            }
        });
    } else {
        requestPermission();
    }
}
 
Example #20
Source File: firebaseutils.java    From LuxVilla with Apache License 2.0 6 votes vote down vote up
public static void updateuserbio(String userbio, final LinearLayout linearLayout){
    FirebaseAuth auth=FirebaseAuth.getInstance();
    FirebaseUser user=auth.getCurrentUser();
    FirebaseDatabase database = FirebaseDatabase.getInstance();

    if (user !=null) {
        DatabaseReference myRef = database.getReference("users").child(user.getUid()).child("user_bio");

        myRef.setValue(userbio).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Snackbar.make(linearLayout,"Lamentamos mas ocorreu um erro",Snackbar.LENGTH_LONG).show();
            }
        });
    }
}
 
Example #21
Source File: DriverMapPresenter.java    From ridesharing-android with MIT License 6 votes vote down vote up
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 #22
Source File: FileMetadataBuilder.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
FileMetadata build() {
    FileMetadata.Builder builder = new FileMetadata.Builder();
    if (uploadTask.getMetadata() != null) {
        builder.setMd5Hash(uploadTask.getMetadata().getMd5Hash())
                .setName(uploadTask.getMetadata().getName())
                .setPath(uploadTask.getMetadata().getPath())
                .setSizeBytes(uploadTask.getMetadata().getSizeBytes())
                .setUpdatedTimeMillis(uploadTask.getMetadata().getUpdatedTimeMillis())
                .setCreationTimeMillis(uploadTask.getMetadata().getCreationTimeMillis())
                .setDownloadUrl(new DownloadUrl(new Consumer<Consumer<String>>() {
                    @Override
                    public void accept(final Consumer<String> stringConsumer) {
                        firebaseStorage.getReference(uploadTask.getMetadata().getPath()).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                stringConsumer.accept(uri.toString());
                            }
                        });
                    }
                }));
    }
    return builder.build();
}
 
Example #23
Source File: MainActivity.java    From Android-9-Development-Cookbook with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        GeofencingClient geofencingClient = LocationServices.getGeofencingClient(this);
        geofencingClient.addGeofences(createGeofencingRequest(), createGeofencePendingIntent())
                .addOnSuccessListener(this, new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(MainActivity.this, "onSuccess()", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MainActivity.this,
                                "onFailure(): " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    } else {
        ActivityCompat.requestPermissions(this,
                new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION},1);
    }
}
 
Example #24
Source File: StorageTest.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Test
public void download1_path() {
    // Given
    Storage storage = new Storage();
    final Task task = Mockito.mock(Task.class);
    when(storageReference.getBytes(Mockito.anyLong())).thenReturn(task);
    when(task.addOnFailureListener(Mockito.any(OnFailureListener.class))).thenReturn(task);
    when(task.addOnSuccessListener(Mockito.any(OnSuccessListener.class))).then(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            ((OnSuccessListener) invocation.getArgument(0)).onSuccess(new byte[0]);
            return task;
        }
    });
    long byteLimit = 1000;

    // When
    storage.download("test", byteLimit).subscribe();

    // Then
    Mockito.verify(storageReference, VerificationModeFactory.times(1)).getBytes(Mockito.anyLong());
    Mockito.verify(task, VerificationModeFactory.times(1)).addOnFailureListener(Mockito.any(OnFailureListener.class));
    Mockito.verify(task, VerificationModeFactory.times(1)).addOnSuccessListener(Mockito.any(OnSuccessListener.class));
}
 
Example #25
Source File: VisionProcessorBase.java    From particle-android with Apache License 2.0 6 votes vote down vote up
private void detectInVisionImage(
        FirebaseVisionImage image,
        final FrameMetadata metadata,
        final GraphicOverlay graphicOverlay) {
    detectInImage(image)
            .addOnSuccessListener(
                    new OnSuccessListener<T>() {
                        @Override
                        public void onSuccess(T results) {
                            shouldThrottle.set(false);
                            VisionProcessorBase.this.onSuccess(results, metadata,
                                    graphicOverlay);
                        }
                    })
            .addOnFailureListener(
                    new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            shouldThrottle.set(false);
                            VisionProcessorBase.this.onFailure(e);
                        }
                    });
    // Begin throttling until this frame of input has been processed, either in onSuccess or
    // onFailure.
    shouldThrottle.set(true);
}
 
Example #26
Source File: ReferralActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void rewardUser(AuthCredential credential) {
    // [START ddl_referral_reward_user]
    FirebaseAuth.getInstance().getCurrentUser()
            .linkWithCredential(credential)
            .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult authResult) {
                    // Complete any post sign-up tasks here.

                    // Trigger the sign-up reward function by creating the
                    // "last_signin_at" field. (If this is a value you want to track,
                    // you would also update this field in the success listeners of
                    // your Firebase Authentication signIn calls.)
                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                    DatabaseReference userRecord =
                            FirebaseDatabase.getInstance().getReference()
                                    .child("users")
                                    .child(user.getUid());
                    userRecord.child("last_signin_at").setValue(ServerValue.TIMESTAMP);
                }
            });
    // [END ddl_referral_reward_user]
}
 
Example #27
Source File: FirebaseDatabaseHelper.java    From Duolingo-Clone with MIT License 6 votes vote down vote up
@Override
public void setLastTimeVisited() {

    if (Injection.providesAuthHelper().getAuthInstance().getCurrentUser() != null) {

        String userID = Injection.providesAuthHelper().getAuthInstance().getCurrentUser().getUid();

        Date date = Calendar.getInstance().getTime();

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY", Locale.US);
        String lastVisited = dateFormat.format(date);

        myRef.child("user")
                .child(userID)
                .child("last_visited")
                .setValue(lastVisited)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                        Log.d(TAG, "Last time user visited has been updated");
                    }
                });
    }
}
 
Example #28
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
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 #29
Source File: PlayGamesPlugin.java    From play_games with MIT License 6 votes vote down vote up
private void signOut() {
    GoogleSignInOptions.Builder builder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
    GoogleSignInOptions opts = builder.build();
    GoogleSignInClient signInClient = GoogleSignIn.getClient(registrar.activity(), opts);
    signInClient.signOut().addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            currentAccount = null;
            Map<String, Object> successMap = new HashMap<>();
            successMap.put("type", "SUCCESS");
            result(successMap);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            error("ERROR_SIGN_OUT", e);
            Log.i(TAG, "Failed to signout", e);
        }
    });

}
 
Example #30
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void getLastLocation() {
  FusedLocationProviderClient fusedLocationClient;
  fusedLocationClient =
    LocationServices.getFusedLocationProviderClient(this);
  if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION)
      == PERMISSION_GRANTED ||
      ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION)
      == PERMISSION_GRANTED) {
    fusedLocationClient.getLastLocation()
      .addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
          updateTextView(location);
        }
      });
  }
}