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

The following examples show how to use com.google.android.gms.tasks.Task#getException() . 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: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 6 votes vote down vote up
@NonNull
private OnCompleteListener<SnapshotsClient.DataOrConflict<Snapshot>> createOpenListener(final String filename) {
  return new OnCompleteListener<SnapshotsClient.DataOrConflict<Snapshot>>() {
    @Override
    public void onComplete(@NonNull Task<SnapshotsClient.DataOrConflict<Snapshot>> task) {
      // if open failed, set the file to closed, otherwise, keep it open.
      if (!task.isSuccessful()) {
        Exception e = task.getException();
        Log.e(TAG, "Open was not a success for filename " + filename, e);
        setClosed(filename);
      } else {
        SnapshotsClient.DataOrConflict<Snapshot> result
            = task.getResult();
        if (result.isConflict()) {
          Log.d(TAG, "Open successful: " + filename + ", but with a conflict");
        } else {
          Log.d(TAG, "Open successful: " + filename);
        }
      }
    }
  };
}
 
Example 2
Source File: ConfigFetchHandler.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Updates last fetch status and last successful fetch time in FRC metadata based on the result of
 * {@code completedFetchTask}.
 */
private void updateLastFetchStatusAndTime(
    Task<FetchResponse> completedFetchTask, Date fetchTime) {
  if (completedFetchTask.isSuccessful()) {
    frcMetadata.updateLastFetchAsSuccessfulAt(fetchTime);
    return;
  }

  Exception fetchException = completedFetchTask.getException();
  if (fetchException == null) {
    // Fetch was cancelled, which should never happen.
    return;
  }

  if (fetchException instanceof FirebaseRemoteConfigFetchThrottledException) {
    frcMetadata.updateLastFetchAsThrottled();
  } else {
    frcMetadata.updateLastFetchAsFailed();
  }
}
 
Example 3
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 4
Source File: TransactionTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionRaisesErrorsForInvalidUpdates() {
  final FirebaseFirestore firestore = testFirestore();

  // Make a transaction that will fail server-side.
  Task<Void> transactionTask =
      firestore.runTransaction(
          transaction -> {
            // Try to read / write a document with an invalid path.
            DocumentSnapshot doc =
                transaction.get(firestore.collection("nonexistent").document("__badpath__"));
            transaction.set(doc.getReference(), map("foo", "value"));
            return null;
          });

  // Let all of the transactions fetch the old value and stop once.
  waitForException(transactionTask);
  assertFalse(transactionTask.isSuccessful());
  Exception e = transactionTask.getException();
  assertNotNull(e);
  FirebaseFirestoreException firestoreException = (FirebaseFirestoreException) e;
  assertEquals(Code.INVALID_ARGUMENT, firestoreException.getCode());
}
 
Example 5
Source File: TransactionTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadAndUpdateNonExistentDocumentWithExternalWrite() {
  FirebaseFirestore firestore = testFirestore();

  // Make a transaction that will fail
  Task<Void> transactionTask =
      firestore.runTransaction(
          transaction -> {
            // Get and update a document that doesn't exist so that the transaction fails.
            DocumentReference doc = firestore.collection("nonexistent").document();
            transaction.get(doc);
            // Do a write outside of the transaction.
            doc.set(map("count", 1234));
            // Now try to update the other doc from within the transaction.
            // This should fail, because the document didn't exist at the
            // start of the transaction.
            transaction.update(doc, "count", 16);
            return null;
          });

  waitForException(transactionTask);
  assertFalse(transactionTask.isSuccessful());
  Exception e = transactionTask.getException();
  assertEquals(Code.INVALID_ARGUMENT, ((FirebaseFirestoreException) e).getCode());
  assertEquals("Can't update a document that doesn't exist.", e.getMessage());
}
 
Example 6
Source File: AttendeeDetailFragment.java    From white-label-event-app with Apache License 2.0 6 votes vote down vote up
@Override
public void onComplete(@NonNull Task<Map<DatabaseReference, DataSnapshot>> task) {
    if (task.isSuccessful()) {
        final Map<DatabaseReference, DataSnapshot> result = task.getResult();
        final Event event = FirebaseDatabaseHelpers.toEvent(result.get(eventRef));
        if (event != null) {
            eventId = event.getId();
        }
        attendeeItem = FirebaseDatabaseHelpers.toAttendeeItem(result.get(attendeeRef));
    }
    else {
        exception = task.getException();
        LOGGER.log(Level.SEVERE, "oops", exception);
    }
    updateUi();
}
 
Example 7
Source File: GeoFireTestingRule.java    From geofire-android with Apache License 2.0 6 votes vote down vote up
public void before(Context context) throws Exception {
    if (FirebaseApp.getApps(context).isEmpty()) {
        FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                .setApplicationId("1:1010498001935:android:f17a2f247ad8e8bc")
                .setApiKey("AIzaSyBys-YxxE7kON5PxZc5aY6JwVvreyx_owc")
                .setDatabaseUrl(databaseUrl)
                .build();
        FirebaseApp.initializeApp(context, firebaseOptions);
        FirebaseDatabase.getInstance().setLogLevel(Logger.Level.DEBUG);
    }

    if (FirebaseAuth.getInstance().getCurrentUser() == null) {
        Task<AuthResult> signInTask = TaskUtils.waitForTask(FirebaseAuth.getInstance().signInAnonymously());
        if (signInTask.isSuccessful()) {
            Log.d(TAG, "Signed in as " + signInTask.getResult().getUser());
        } else {
            throw new Exception("Failed to sign in: " + signInTask.getException());
        }
    }

    this.databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(databaseUrl);
}
 
Example 8
Source File: LoginPresenter.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void handleAuthError(Task<AuthResult> task) {
    Exception exception = task.getException();
    LogUtil.logError(TAG, "signInWithCredential", exception);

    ifViewAttached(view -> {
        if (exception != null) {
            view.showWarningDialog(exception.getMessage());
        } else {
            view.showSnackBar(R.string.error_authentication);
        }

        view.hideProgress();
    });
}
 
Example 9
Source File: CompaniesFragment.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<CompanyItem> companies = FirebaseDatabaseHelpers.toCompaniesSection(task.getResult().get(companiesRef));
        items = new ArrayList<>(companies.getItems().values());
        Collections.sort(items, CompanyItems.POSITION_COMPARATOR);
    }
    else {
        exception = task.getException();
        LOGGER.log(Level.SEVERE, "oops", exception);
    }
    updateUi();
}
 
Example 10
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 11
Source File: CompanyDetailFragment.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()) {
        companyItem = FirebaseDatabaseHelpers.toCompanyItem(task.getResult().get(companyRef));
    }
    else {
        exception = task.getException();
        LOGGER.log(Level.SEVERE, "oops", exception);
    }
    updateUi();
}
 
Example 12
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 13
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 14
Source File: Utils.java    From google-signin with MIT License 5 votes vote down vote up
public static int getExceptionCode(@NonNull Task<Void> task) {
    Exception e = task.getException();

    if (e instanceof ApiException) {
        ApiException exception = (ApiException) e;
        return exception.getStatusCode();
    }
    return CommonStatusCodes.INTERNAL_ERROR;
}
 
Example 15
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 16
Source File: LoginPresenter.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void handleAuthError(Task<AuthResult> task) {
    Exception exception = task.getException();
    LogUtil.logError(TAG, "signInWithCredential", exception);

    ifViewAttached(view -> {
        if (exception != null) {
            view.showWarningDialog(exception.getMessage());
        } else {
            view.showSnackBar(R.string.error_authentication);
        }

        view.hideProgress();
    });
}
 
Example 17
Source File: FirestoreTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testClearPersistenceWhileRunningFails() {
  FirebaseFirestore firestore = testFirestore();
  waitFor(firestore.enableNetwork());

  Task<Void> transactionTask = AccessHelper.clearPersistence(firestore);
  waitForException(transactionTask);
  assertFalse(transactionTask.isSuccessful());
  Exception e = transactionTask.getException();
  FirebaseFirestoreException firestoreException = (FirebaseFirestoreException) e;
  assertEquals(Code.FAILED_PRECONDITION, firestoreException.getCode());
}
 
Example 18
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 19
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();
}