Java Code Examples for com.google.android.gms.tasks.Task#isSuccessful()

The following examples show how to use com.google.android.gms.tasks.Task#isSuccessful() . 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: Utils.java    From firebase-android-sdk with Apache License 2.0 7 votes vote down vote up
/** @return A tasks that is resolved when either of the given tasks is resolved. */
public static <T> Task<T> race(Task<T> t1, Task<T> t2) {
  final TaskCompletionSource<T> result = new TaskCompletionSource<>();
  Continuation<T, Void> continuation =
      new Continuation<T, Void>() {
        @Override
        public Void then(@NonNull Task<T> task) throws Exception {
          if (task.isSuccessful()) {
            result.trySetResult(task.getResult());
          } else {
            result.trySetException(task.getException());
          }
          return null;
        }
      };
  t1.continueWith(continuation);
  t2.continueWith(continuation);
  return result.getTask();
}
 
Example 2
Source File: BaseDemoActivity.java    From android-samples with Apache License 2.0 7 votes vote down vote up
/**
 * Handles resolution callbacks.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQUEST_CODE_SIGN_IN:
            if (resultCode != RESULT_OK) {
                // Sign-in may fail or be cancelled by the user. For this sample, sign-in is
                // required and is fatal. For apps where sign-in is optional, handle
                // appropriately
                Log.e(TAG, "Sign-in failed.");
                finish();
                return;
            }

            Task<GoogleSignInAccount> getAccountTask =
                GoogleSignIn.getSignedInAccountFromIntent(data);
            if (getAccountTask.isSuccessful()) {
                initializeDriveClient(getAccountTask.getResult());
            } else {
                Log.e(TAG, "Sign-in failed.");
                finish();
            }
            break;
        case REQUEST_CODE_OPEN_ITEM:
            if (resultCode == RESULT_OK) {
                DriveId driveId = data.getParcelableExtra(
                        OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
                mOpenItemTaskSource.setResult(driveId);
            } else {
                mOpenItemTaskSource.setException(new RuntimeException("Unable to open file"));
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 3
Source File: AndroidGoogleAccount.java    From QtAndroidTools with MIT License 6 votes vote down vote up
public boolean signIn(String ScopeName)
{
    if(mGoogleSignInClient == null)
    {
        Task<GoogleSignInAccount> SignInTask;

        mGoogleSignInClient = getSignInClient(ScopeName);

        SignInTask = mGoogleSignInClient.silentSignIn();
        if(SignInTask.isSuccessful())
        {
            loadSignedInAccountInfo(SignInTask.getResult());
            signedIn(true);
        }
        else
        {
            SignInTask.addOnCompleteListener(mActivityInstance, new SignInAccountListener());
        }

        return true;
    }

    return false;
}
 
Example 4
Source File: MainActivity.java    From android-credentials with Apache License 2.0 6 votes vote down vote up
private void googleSilentSignIn() {
    // Try silent sign-in with Google Sign In API
    Task<GoogleSignInAccount> silentSignIn = mSignInClient.silentSignIn();

    if (silentSignIn.isComplete() && silentSignIn.isSuccessful()) {
        handleGoogleSignIn(silentSignIn);
        return;
    }

    showProgress();
    silentSignIn.addOnCompleteListener(new OnCompleteListener<GoogleSignInAccount>() {
        @Override
        public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
            hideProgress();
            handleGoogleSignIn(task);
        }
    });
}
 
Example 5
Source File: AndroidGoogleAccount.java    From QtAndroidTools with MIT License 6 votes vote down vote up
public boolean revokeAccess()
{
    if(mGoogleSignInClient != null)
    {
        final Task<Void> SignOutTask = mGoogleSignInClient.revokeAccess();

        if(SignOutTask.isSuccessful())
        {
            updateSignedInAccountInfo(null);
            mGoogleSignInClient = null;
            signedOut();
        }
        else
        {
            SignOutTask.addOnCompleteListener(mActivityInstance, new SignOutAccountListener());
        }

        return true;
    }

    return false;
}
 
Example 6
Source File: ConfigCacheClient.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Reimplementation of {@link Tasks#await(Task, long, TimeUnit)} because that method has a
 * precondition that fails when run on the main thread.
 *
 * <p>This blocking method is required because the current FRC API has synchronous getters that
 * read from a cache that is loaded from disk. In other words, the synchronous methods rely on an
 * async task, so the getters have to block at some point.
 *
 * <p>Until the next breaking change in the API, this use case must be implemented, even though it
 * is against Android best practices.
 */
private static <TResult> TResult await(Task<TResult> task, long timeout, TimeUnit unit)
    throws ExecutionException, InterruptedException, TimeoutException {
  AwaitListener<TResult> waiter = new AwaitListener<>();

  task.addOnSuccessListener(DIRECT_EXECUTOR, waiter);
  task.addOnFailureListener(DIRECT_EXECUTOR, waiter);
  task.addOnCanceledListener(DIRECT_EXECUTOR, waiter);

  if (!waiter.await(timeout, unit)) {
    throw new TimeoutException("Task await timed out.");
  }

  if (task.isSuccessful()) {
    return task.getResult();
  } else {
    throw new ExecutionException(task.getException());
  }
}
 
Example 7
Source File: FirebaseRemoteConfig.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Processes the result of the put task that persists activated configs. If the task is
 * successful, clears the fetched cache and updates the ABT SDK with the current experiments.
 *
 * @param putTask the {@link Task} returned by a {@link ConfigCacheClient#put(ConfigContainer)}
 *     call on {@link #activatedConfigsCache}.
 * @return True if {@code putTask} was successful, false otherwise.
 */
private boolean processActivatePutTask(Task<ConfigContainer> putTask) {
  if (putTask.isSuccessful()) {
    fetchedConfigsCache.clear();

    // An activate call should only be made if there are fetched values to activate, which are
    // then put into the activated cache. So, if the put is called and succeeds, then the returned
    // values from the put task must be non-null.
    if (putTask.getResult() != null) {
      updateAbtWithActivatedExperiments(putTask.getResult().getAbtExperiments());
    } else {
      // Should never happen.
      Log.e(TAG, "Activated configs written to disk are null.");
    }
    return true;
  }
  return false;
}
 
Example 8
Source File: TestOnCompleteListener.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete(@NonNull Task<TResult> task) {
  this.task = task;
  successful = task.isSuccessful();
  if (successful) {
    result = task.getResult();
  } else {
    exception = task.getException();
  }
  latch.countDown();
}
 
Example 9
Source File: MapsFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete(@NonNull Task<Map<DatabaseReference, DataSnapshot>> task) {
    if (task.isSuccessful()) {
        final Section<MapItem> maps = FirebaseDatabaseHelpers.toMapsSection(task.getResult().get(mapsRef));
        mapItems = new ArrayList<>(maps.getItems().values());
    }
    else {
        exception = task.getException();
        LOGGER.log(Level.SEVERE, "oops", exception);
    }
    updateUi();
}
 
Example 10
Source File: CompletionLiveData.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
@Override
public final void onComplete(@NonNull Task<Void> task) {
    if (task.isSuccessful()) {
        setValue(new Resource<>(true));
    } else {
        setValue(new Resource<>(task.getException()));
    }
}
 
Example 11
Source File: ManageAccountActivity.java    From wmn-safety with MIT License 5 votes vote down vote up
public void updateAccount(View view) {
    OnCompleteListener<Void> listener = new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Toast.makeText(getApplicationContext(), "Account Update Successful", Toast.LENGTH_SHORT).show();
            } else {
                Log.e("Update Failed", task.getException() + "");
                Toast.makeText(getApplicationContext(), "Account Update Failed", Toast.LENGTH_SHORT).show();
            }
        }
    };
    String name = ((EditText) (findViewById(R.id.account_update_full_name))).getText().toString();
    String email = ((EditText) (findViewById(R.id.account_update_email))).getText().toString();
    String phone = ((EditText) (findViewById(R.id.account_update_phone))).getText().toString();
    String UID = mFirebaseUser.getUid();
    DatabaseReference reference = mDatabaseReference.child(UID);
    Map<String, Object> updates = new HashMap<>();
    if (!name.isEmpty()) {
        updates.put("/name", name);
    }
    if (!email.isEmpty()) {
        mFirebaseUser.updateEmail(email).addOnCompleteListener(this, listener);
        updates.put("/email", email);
    }
    if (!phone.isEmpty()) {
        updates.put("/number", phone);
    }
    reference.updateChildren(updates).addOnCompleteListener(this, listener);
    Intent intent = this.getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
    if (intent != null) {
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    }
    startActivity(intent);
}
 
Example 12
Source File: EventInfoFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete(@NonNull Task<Map<DatabaseReference, DataSnapshot>> task) {
    if (task.isSuccessful()) {
        event = FirebaseDatabaseHelpers.toEvent(task.getResult().get(eventRef));
    }
    else {
        exception = task.getException();
        LOGGER.log(Level.SEVERE, "oops", exception);
    }
    updateUi();
}
 
Example 13
Source File: MainActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
private void handleGoogleSignIn(Task<GoogleSignInAccount> completedTask) {
    Log.d(TAG, "handleGoogleSignIn:" + completedTask);

    boolean isSignedIn = (completedTask != null) && completedTask.isSuccessful();
    if (isSignedIn) {
        // Display signed-in UI
        GoogleSignInAccount gsa = completedTask.getResult();
        String status = String.format("Signed in as %s (%s)", gsa.getDisplayName(),
                gsa.getEmail());
        ((TextView) findViewById(R.id.text_google_status)).setText(status);

        // Save Google Sign In to SmartLock
        Credential credential = new Credential.Builder(gsa.getEmail())
                .setAccountType(IdentityProviders.GOOGLE)
                .setName(gsa.getDisplayName())
                .setProfilePictureUri(gsa.getPhotoUrl())
                .build();

        saveCredential(credential);
    } else {
        // Display signed-out UI
        ((TextView) findViewById(R.id.text_google_status)).setText(R.string.signed_out);
    }

    findViewById(R.id.button_google_sign_in).setEnabled(!isSignedIn);
    findViewById(R.id.button_google_sign_out).setEnabled(isSignedIn);
    findViewById(R.id.button_google_revoke).setEnabled(isSignedIn);
}
 
Example 14
Source File: StorageReference.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * List all items (files) and prefixes (folders) under this StorageReference.
 *
 * <p>This is a helper method for calling {@code list()} repeatedly until there are no more
 * results. Consistency of the result is not guaranteed if objects are inserted or removed while
 * this operation is executing.
 *
 * <p>{@code listAll()} is only available for projects using <a
 * href="https://firebase.google.com/docs/rules/rules-behavior#security_rules_version_2">Firebase
 * Rules Version 2</a>.
 *
 * @throws OutOfMemoryError If there are too many items at this location.
 * @return A {@link Task} that returns all items and prefixes under the current StorageReference.
 */
@NonNull
public Task<ListResult> listAll() {
  TaskCompletionSource<ListResult> pendingResult = new TaskCompletionSource<>();

  List<StorageReference> prefixes = new ArrayList<>();
  List<StorageReference> items = new ArrayList<>();

  Executor executor = StorageTaskScheduler.getInstance().getCommandPoolExecutor();
  Task<ListResult> list = listHelper(/* maxResults= */ null, /* pageToken= */ null);

  Continuation<ListResult, Task<Void>> continuation =
      new Continuation<ListResult, Task<Void>>() {
        @Override
        public Task<Void> then(@NonNull Task<ListResult> currentPage) {
          if (currentPage.isSuccessful()) {
            ListResult result = currentPage.getResult();
            prefixes.addAll(result.getPrefixes());
            items.addAll(result.getItems());

            if (result.getPageToken() != null) {
              Task<ListResult> nextPage =
                  listHelper(/* maxResults= */ null, result.getPageToken());
              nextPage.continueWithTask(executor, this);
            } else {
              pendingResult.setResult(new ListResult(prefixes, items, /* pageToken= */ null));
            }
          } else {
            pendingResult.setException(currentPage.getException());
          }

          return Tasks.forResult(null);
        }
      };

  list.continueWithTask(executor, continuation);

  return pendingResult.getTask();
}
 
Example 15
Source File: SessionReportingCoordinator.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private boolean onReportSendComplete(@NonNull Task<CrashlyticsReportWithSessionId> task) {
  if (task.isSuccessful()) {
    // TODO: Consolidate sending analytics event here, which will capture both native and
    // non-native fatal reports
    final CrashlyticsReportWithSessionId report = task.getResult();
    Logger.getLogger()
        .d("Crashlytics report successfully enqueued to DataTransport: " + report.getSessionId());
    reportPersistence.deleteFinalizedReport(report.getSessionId());
    return true;
  }
  Logger.getLogger()
      .d("Crashlytics report could not be enqueued to DataTransport", task.getException());
  return false;
}
 
Example 16
Source File: LoginPresenter.java    From FastAccess with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Override public void onComplete(@NonNull Task<AuthResult> task) {
    Logger.e(task.isSuccessful(), task.isComplete());
    if (isAttached()) {
        if (!task.isSuccessful()) {
            if (task.getException() != null && task.getException().getMessage() != null) {
                getView().onShowMessage(task.getException().getMessage());
            } else {
                getView().onShowMessage(R.string.failed_login);
            }
        }
    }
}
 
Example 17
Source File: MainActivity.java    From PixelWatchFace with GNU General Public License v3.0 5 votes vote down vote up
private void syncToWear() {
  //Toast.makeText(this, "something changed, syncing to watch", Toast.LENGTH_SHORT).show();
  Snackbar.make(findViewById(android.R.id.content), "Syncing to watch...", Snackbar.LENGTH_SHORT)
      .show();
  loadPreferences();
  String TAG = "syncToWear";
  DataClient mDataClient = Wearable.getDataClient(this);
  PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/settings");

      /* Reference DataMap retrieval code on the WearOS app
              mShowTemperature = dataMap.getBoolean("show_temperature");
              mUseCelsius = dataMap.getBoolean("use_celsius");
              mShowWeather = dataMap.getBoolean("show_weather");
              */

  putDataMapReq.getDataMap().putLong("timestamp", System.currentTimeMillis());
  putDataMapReq.getDataMap().putBoolean("show_temperature", showTemperature);
  putDataMapReq.getDataMap().putBoolean("use_celsius", useCelsius);
  putDataMapReq.getDataMap().putBoolean("show_weather", showWeather);
  putDataMapReq.getDataMap().putBoolean("show_temperature_decimal", showTemperatureDecimalPoint);
  putDataMapReq.getDataMap().putBoolean("use_thin", useThin);
  putDataMapReq.getDataMap().putBoolean("use_thin_ambient", useThinAmbient);
  putDataMapReq.getDataMap().putBoolean("use_gray_info_ambient", useGrayInfoAmbient);
  putDataMapReq.getDataMap().putBoolean("show_infobar_ambient", showInfoBarAmbient);
  putDataMapReq.getDataMap().putString("dark_sky_api_key", darkSkyAPIKey);
  putDataMapReq.getDataMap().putBoolean("use_dark_sky", useDarkSky);
  putDataMapReq.getDataMap().putBoolean("show_battery", showBattery);
  putDataMapReq.getDataMap().putBoolean("show_wear_icon", showWearIcon);
  putDataMapReq.getDataMap().putBoolean("advanced", advanced);

  putDataMapReq.setUrgent();
  Task<DataItem> putDataTask = mDataClient.putDataItem(putDataMapReq.asPutDataRequest());
  if (putDataTask.isSuccessful()) {
    Log.d(TAG, "Settings synced to wearable");
  }
}
 
Example 18
Source File: SignInResultNotifier.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
    if (task.isSuccessful()) {
        Toast.makeText(mContext, R.string.signed_in, Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(mContext, R.string.anonymous_auth_failed_msg, Toast.LENGTH_LONG).show();
    }
}
 
Example 19
Source File: AttendeesFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete(@NonNull Task<Map<DatabaseReference, DataSnapshot>> task) {
    if (task.isSuccessful()) {
        final Section<AttendeeItem> attendeesSection = FirebaseDatabaseHelpers.toAttendeesSection(task.getResult().get(attendeesRef));
        items = new ArrayList<>(attendeesSection.getItems().values());
        Collections.sort(items, AttendeeItems.NAME_COMPARATOR);
    }
    else {
        exception = task.getException();
        LOGGER.log(Level.SEVERE, "oops", exception);
    }
    updateUi();
}
 
Example 20
Source File: MainActivity.java    From identity-samples with Apache License 2.0 5 votes vote down vote up
private void handleGoogleSignIn(Task<GoogleSignInAccount> completedTask) {
    Log.d(TAG, "handleGoogleSignIn:" + completedTask);

    boolean isSignedIn = (completedTask != null) && completedTask.isSuccessful();
    if (isSignedIn) {
        // Display signed-in UI
        GoogleSignInAccount gsa = completedTask.getResult();
        String status = String.format("Signed in as %s (%s)", gsa.getDisplayName(),
                gsa.getEmail());
        ((TextView) findViewById(R.id.text_google_status)).setText(status);

        // Save Google Sign In to SmartLock
        Credential credential = new Credential.Builder(gsa.getEmail())
                .setAccountType(IdentityProviders.GOOGLE)
                .setName(gsa.getDisplayName())
                .setProfilePictureUri(gsa.getPhotoUrl())
                .build();

        saveCredential(credential);
    } else {
        // Display signed-out UI
        ((TextView) findViewById(R.id.text_google_status)).setText(R.string.signed_out);
    }

    findViewById(R.id.button_google_sign_in).setEnabled(!isSignedIn);
    findViewById(R.id.button_google_sign_out).setEnabled(isSignedIn);
    findViewById(R.id.button_google_revoke).setEnabled(isSignedIn);
}