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

The following examples show how to use com.google.android.gms.tasks.Task#getResult() . 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: PurchaseActivity.java    From YTPlayer with GNU General Public License v3.0 8 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            Toast.makeText(this, "Failed to sign in, Error: "+e.getStatusCode(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            Log.e(TAG, "signInResult:failed code=" + e.getStatusCode());
        }
    }
    if (requestCode == 104) {
        if (resultCode==1) {
            boolean isPaid = data.getBooleanExtra("payment",false);
            if (isPaid) {
                setSuccess(data.getStringExtra("client"),
                        FirebaseDatabase.getInstance().getReference("orders"));
            }
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 2
Source File: GameSyncService.java    From Passbook with Apache License 2.0 7 votes vote down vote up
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
    if(requestCode == CA.AUTH) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            mSignInAccount = task.getResult(ApiException.class);
            mSnapshotClient = Games.getSnapshotsClient(activity, mSignInAccount);
            mListener.onSyncProgress(CA.AUTH);
            read();
        } catch (ApiException e) {
            mListener.onSyncFailed(CA.CONNECTION);
        }
    }
}
 
Example 3
Source File: GoogleProviderHandler.java    From capacitor-firebase-auth with MIT License 6 votes vote down vote up
@Override
public void handleOnActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(GOOGLE_TAG, "Google SignIn activity result.");

    try {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        // Google Sign In was successful, authenticate with Firebase
        GoogleSignInAccount account = task.getResult(ApiException.class);

        if (account != null) {
            Log.d(GOOGLE_TAG, "Google Sign In succeed.");
            AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
            this.plugin.handleAuthCredentials(credential);
            return;
        }
    } catch (ApiException exception) {
        // Google Sign In failed, update UI appropriately
        Log.w(GOOGLE_TAG, GoogleSignInStatusCodes.getStatusCodeString(exception.getStatusCode()), exception);
        plugin.handleFailure("Google Sign In failure.", exception);
        return;
    }

    plugin.handleFailure("Google Sign In failure.", null);
}
 
Example 4
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 5
Source File: GoogleSignInActivity.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
@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);
            Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
            firebaseAuthWithGoogle(account.getIdToken());
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Google sign in failed", e);
            // [START_EXCLUDE]
            updateUI(null);
            // [END_EXCLUDE]
        }
    }
}
 
Example 6
Source File: SignInActivity.java    From codelab-friendlychat-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent in signIn()
    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);
        }
    }
}
 
Example 7
Source File: StorageTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void getShouldReturnNewlyPutData() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseStorage storage = FirebaseStorage.getInstance();

  auth.signOut();
  Task<?> signInTask = auth.signInWithEmailAndPassword("[email protected]", "password");
  Tasks2.waitForSuccess(signInTask);

  StorageReference blob = storage.getReference("restaurants").child(TestId.create());

  byte[] data = "Google NYC".getBytes(StandardCharsets.UTF_8);

  try {
    Task<?> putTask = blob.putBytes(Arrays.copyOf(data, data.length));
    Tasks2.waitForSuccess(putTask);

    Task<byte[]> getTask = blob.getBytes(128);
    Tasks2.waitForSuccess(getTask);

    byte[] result = getTask.getResult();
    assertThat(result).isEqualTo(data);
  } finally {
    Tasks2.waitBestEffort(blob.delete());
  }
}
 
Example 8
Source File: SourceTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void getNonExistingCollectionWhileOnlineWithSourceEqualToCache() {
  CollectionReference colRef = testCollection();

  Task<QuerySnapshot> qrySnapTask = colRef.get(Source.CACHE);
  waitFor(qrySnapTask);

  QuerySnapshot qrySnap = qrySnapTask.getResult();
  assertTrue(qrySnap.isEmpty());
  assertEquals(0, qrySnap.getDocumentChanges().size());
  assertTrue(qrySnap.getMetadata().isFromCache());
  assertFalse(qrySnap.getMetadata().hasPendingWrites());
}
 
Example 9
Source File: SourceTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void getDocumentWhileOfflineWithDifferentGetOptions() {
  Map<String, Object> initialData = map("key", "value");
  DocumentReference docRef = testDocumentWithData(initialData);

  waitFor(docRef.get());
  waitFor(docRef.getFirestore().disableNetwork());

  // Create an initial listener for this query (to attempt to disrupt the gets below) and wait for
  // the listener to deliver its initial snapshot before continuing.
  TaskCompletionSource<Void> source = new TaskCompletionSource<>();
  docRef.addSnapshotListener(
      (docSnap, error) -> {
        if (error != null) {
          source.setException(error);
        } else {
          source.setResult(null);
        }
      });
  waitFor(source.getTask());

  Task<DocumentSnapshot> docTask = docRef.get(Source.CACHE);
  waitFor(docTask);
  DocumentSnapshot doc = docTask.getResult();
  assertTrue(doc.exists());
  assertTrue(doc.getMetadata().isFromCache());
  assertFalse(doc.getMetadata().hasPendingWrites());
  assertEquals(initialData, doc.getData());

  docTask = docRef.get();
  waitFor(docTask);
  doc = docTask.getResult();
  assertTrue(doc.exists());
  assertTrue(doc.getMetadata().isFromCache());
  assertFalse(doc.getMetadata().hasPendingWrites());
  assertEquals(initialData, doc.getData());

  docTask = docRef.get(Source.SERVER);
  waitForException(docTask);
}
 
Example 10
Source File: SourceTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void getDocumentWhileOnlineWithDefaultGetOptions() {
  Map<String, Object> initialData = map("key", "value");
  DocumentReference docRef = testDocumentWithData(initialData);

  Task<DocumentSnapshot> docTask = docRef.get();
  waitFor(docTask);

  DocumentSnapshot doc = docTask.getResult();
  assertTrue(doc.exists());
  assertFalse(doc.getMetadata().isFromCache());
  assertFalse(doc.getMetadata().hasPendingWrites());
  assertEquals(initialData, doc.getData());
}
 
Example 11
Source File: FirestoreTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void setShouldTriggerListenerWithNewlySetData() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseFirestore firestore = FirebaseFirestore.getInstance();

  auth.signOut();
  Task<?> signInTask = auth.signInWithEmailAndPassword("[email protected]", "password");
  Tasks2.waitForSuccess(signInTask);

  DocumentReference doc = firestore.collection("restaurants").document(TestId.create());
  SnapshotListener listener = new SnapshotListener();
  ListenerRegistration registration = doc.addSnapshotListener(listener);

  try {
    HashMap<String, Object> data = new HashMap<>();
    data.put("location", "Google NYC");

    Task<?> setTask = doc.set(new HashMap<>(data));
    Task<DocumentSnapshot> snapshotTask = listener.toTask();
    Tasks2.waitForSuccess(setTask);
    Tasks2.waitForSuccess(snapshotTask);

    DocumentSnapshot result = snapshotTask.getResult();
    assertThat(result.getData()).isEqualTo(data);
  } finally {
    registration.remove();
    Tasks2.waitBestEffort(doc.delete());
  }
}
 
Example 12
Source File: DatabaseTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void setValueShouldTriggerListenerWithNewlySetData() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseDatabase database = FirebaseDatabase.getInstance();

  auth.signOut();
  Task<?> signInTask = auth.signInWithEmailAndPassword("[email protected]", "password");
  Tasks2.waitForSuccess(signInTask);

  DatabaseReference doc = database.getReference("restaurants").child(TestId.create());
  SnapshotListener listener = new SnapshotListener();
  doc.addListenerForSingleValueEvent(listener);

  HashMap<String, Object> data = new HashMap<>();
  data.put("location", "Google NYC");

  try {
    Task<?> setTask = doc.setValue(new HashMap<>(data));
    Task<DataSnapshot> snapshotTask = listener.toTask();
    Tasks2.waitForSuccess(setTask);
    Tasks2.waitForSuccess(snapshotTask);

    DataSnapshot result = snapshotTask.getResult();
    assertThat(result.getValue()).isEqualTo(data);
  } finally {
    Tasks2.waitBestEffort(doc.removeValue());
  }
}
 
Example 13
Source File: FirebaseDynamicLinksImplTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDynamicLink_IntentWithDynamicLinkData() {
  Bundle extensions = new Bundle();
  extensions.putString(PARAMETER, VALUE);
  DynamicLinkData dynamicLinkData =
      new DynamicLinkData(
          DYNAMIC_LINK,
          DEEP_LINK,
          MINIMUM_VERSION,
          CLICK_TIMESTAMP,
          extensions,
          null /* redirectUrl */);
  Intent intent = new Intent();
  SafeParcelableSerializer.serializeToIntentExtra(
      dynamicLinkData, intent, EXTRA_DYNAMIC_LINK_DATA);

  Task<PendingDynamicLinkData> task = api.getDynamicLink(intent);
  verify(mockGoogleApi)
      .doWrite(ArgumentMatchers.<TaskApiCall<DynamicLinksClient, PendingDynamicLinkData>>any());
  assertTrue(task.isComplete());
  assertTrue(task.isSuccessful());
  PendingDynamicLinkData pendingDynamicLinkData = task.getResult();
  assertNotNull(pendingDynamicLinkData);
  assertEquals(Uri.parse(DEEP_LINK), pendingDynamicLinkData.getLink());
  assertEquals(MINIMUM_VERSION, pendingDynamicLinkData.getMinimumAppVersion());
  assertEquals(CLICK_TIMESTAMP, pendingDynamicLinkData.getClickTimestamp());
  Bundle returnExtensions = pendingDynamicLinkData.getExtensions();
  assertEquals(extensions.keySet(), returnExtensions.keySet());
  for (String key : extensions.keySet()) {
    assertEquals(extensions.getString(key), returnExtensions.getString(key));
  }
  assertNull(pendingDynamicLinkData.getRedirectUrl());
}
 
Example 14
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 15
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 16
Source File: SourceTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void getCollectionWhileOfflineWithSourceEqualToCache() {
  Map<String, Map<String, Object>> initialDocs =
      map(
          "doc1", map("key1", "value1"),
          "doc2", map("key2", "value2"),
          "doc3", map("key3", "value3"));
  CollectionReference colRef = testCollectionWithDocs(initialDocs);

  waitFor(colRef.get());
  waitFor(colRef.getFirestore().disableNetwork());

  // Since we're offline, the returned promises won't complete
  colRef.document("doc2").set(map("key2b", "value2b"), SetOptions.merge());
  colRef.document("doc3").set(map("key3b", "value3b"));
  colRef.document("doc4").set(map("key4", "value4"));

  Task<QuerySnapshot> qrySnapTask = colRef.get(Source.CACHE);
  waitFor(qrySnapTask);

  QuerySnapshot qrySnap = qrySnapTask.getResult();
  assertTrue(qrySnap.getMetadata().isFromCache());
  assertTrue(qrySnap.getMetadata().hasPendingWrites());
  assertEquals(4, qrySnap.getDocumentChanges().size());
  assertEquals(
      map(
          "doc1", map("key1", "value1"),
          "doc2", map("key2", "value2", "key2b", "value2b"),
          "doc3", map("key3b", "value3b"),
          "doc4", map("key4", "value4")),
      toDataMap(qrySnap));
}
 
Example 17
Source File: GoogleSignInActivity.java    From wear-os-samples with Apache License 2.0 5 votes vote down vote up
protected void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);

        // Signed in successfully, show authenticated UI.
        updateUi(account);
    } catch (ApiException e) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Log.w(TAG,
                "signInResult:failed code=" + e.getStatusCode() + ". Msg=" + GoogleSignInStatusCodes.getStatusCodeString(e.getStatusCode()));
        updateUi(null);
    }
}
 
Example 18
Source File: ThreadsListFragmentPresenter.java    From demo-firebase-android with The Unlicense 5 votes vote down vote up
private void updateThreads(QuerySnapshot documentSnapshots, Task<DocumentSnapshot> task) {
    if (task.isSuccessful()) {
        DocumentSnapshot documentSnapshot = task.getResult();

        DefaultUser defaultUser = documentSnapshot.toObject(DefaultUser.class);
        defaultUser.setName(documentSnapshot.getId());

        List<DefaultChatThread> threads = new ArrayList<>();

        for (String channelId : defaultUser.getChannels()) {
            for (DocumentSnapshot document : documentSnapshots) {
                if (document.getId().equals(channelId)) {
                    List<String> members = (List<String>) document.get(KEY_PROPERTY_MEMBERS);
                    long messagesCount = (Long) document.get(KEY_PROPERTY_COUNT);

                    String senderId = members.get(0).equals(firebaseAuth.getCurrentUser()
                                                                        .getEmail()
                                                                        .toLowerCase()
                                                                        .split("@")[0])
                                      ? members.get(0) : members.get(1);
                    String receiverId = members.get(0)
                                               .equals(senderId) ? members.get(1)
                                                                 : members.get(0);
                    threads.add(new DefaultChatThread(document.getId(),
                                                      senderId,
                                                      receiverId,
                                                      messagesCount));
                }
            }
        }

        onDataReceivedInteractor.onDataReceived(threads);
    } else {
        onDataReceivedInteractor.onDataReceivedError(task.getException());
    }
}
 
Example 19
Source File: TestUtil.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public static <T> T waitFor(Task<T> task) {
  if (!task.isComplete()) {
    Robolectric.flushBackgroundThreadScheduler();
  }
  Assert.assertTrue(
      "Expected task to be completed after background thread flush", task.isComplete());
  return task.getResult();
}
 
Example 20
Source File: MainActivity.java    From android-basic-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

  if (requestCode == RC_SIGN_IN) {

    Task<GoogleSignInAccount> task =
        GoogleSignIn.getSignedInAccountFromIntent(intent);

    try {
      GoogleSignInAccount account = task.getResult(ApiException.class);
      onConnected(account);
    } catch (ApiException apiException) {
      String message = apiException.getMessage();
      if (message == null || message.isEmpty()) {
        message = getString(R.string.signin_other_error);
      }

      onDisconnected();

      new AlertDialog.Builder(this)
          .setMessage(message)
          .setNeutralButton(android.R.string.ok, null)
          .show();
    }
  } else if (requestCode == RC_SELECT_PLAYERS) {
    // we got the result from the "select players" UI -- ready to create the room
    handleSelectPlayersResult(resultCode, intent);

  } else if (requestCode == RC_INVITATION_INBOX) {
    // we got the result from the "select invitation" UI (invitation inbox). We're
    // ready to accept the selected invitation:
    handleInvitationInboxResult(resultCode, intent);

  } else if (requestCode == RC_WAITING_ROOM) {
    // we got the result from the "waiting room" UI.
    if (resultCode == Activity.RESULT_OK) {
      // ready to start playing
      Log.d(TAG, "Starting game (waiting room returned OK).");
      startGame(true);
    } else if (resultCode == GamesActivityResultCodes.RESULT_LEFT_ROOM) {
      // player indicated that they want to leave the room
      leaveRoom();
    } else if (resultCode == Activity.RESULT_CANCELED) {
      // Dialog was cancelled (user pressed back key, for instance). In our game,
      // this means leaving the room too. In more elaborate games, this could mean
      // something else (like minimizing the waiting room UI).
      leaveRoom();
    }
  }
  super.onActivityResult(requestCode, resultCode, intent);
}