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

The following examples show how to use com.google.android.gms.tasks.Task. 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: FirebaseMultiQuery.java    From white-label-event-app with Apache License 2.0 7 votes vote down vote up
public Task<Map<DatabaseReference, DataSnapshot>> start() {
    // Create a Task<DataSnapshot> to trigger in response to each database listener.
    //
    final ArrayList<Task<DataSnapshot>> tasks = new ArrayList<>(refs.size());
    for (final DatabaseReference ref : refs) {
        final TaskCompletionSource<DataSnapshot> source = new TaskCompletionSource<>();
        final ValueEventListener listener = new MyValueEventListener(ref, source);
        ref.addListenerForSingleValueEvent(listener);
        listeners.put(ref, listener);
        tasks.add(source.getTask());
    }

    // Return a single Task that triggers when all queries are complete.  It contains
    // a map of all original DatabaseReferences originally given here to their resulting
    // DataSnapshot.
    //
    return Tasks.whenAll(tasks).continueWith(new Continuation<Void, Map<DatabaseReference, DataSnapshot>>() {
        @Override
        public Map<DatabaseReference, DataSnapshot> then(@NonNull Task<Void> task) throws Exception {
            task.getResult();
            return new HashMap<>(snaps);
        }
    });
}
 
Example #2
Source File: SettingsFragment.java    From YTPlayer with GNU General Public License v3.0 7 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode==103) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            Toast.makeText(activity, "Failed to sign in, Error: "+e.getStatusCode(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            Log.e(TAG, "signInResult:failed code=" + e.getStatusCode());
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example #3
Source File: FCMRegistration.java    From Android-SDK with MIT License 6 votes vote down vote up
static void unregisterDeviceOnFCM(final Context context, final AsyncCallback<Integer> callback)
{
  FirebaseMessaging.getInstance().unsubscribeFromTopic( DEFAULT_TOPIC ).addOnCompleteListener( new OnCompleteListener<Void>()
  {
    @Override
    public void onComplete( @NonNull Task<Void> task )
    {
      if( task.isSuccessful() )
      {
        Log.d( TAG, "Unsubscribed on FCM." );
        if( callback != null )
          callback.handleResponse( 0 );
      }
      else
      {
        Log.e( TAG, "Failed to unsubscribe in FCM.", task.getException() );
        String reason = (task.getException() != null) ? Objects.toString( task.getException().getMessage() ) : "";
        if( callback != null )
          callback.handleFault( new BackendlessFault( "Failed to unsubscribe on FCM. " + reason ) );
      }
    }
  } );
}
 
Example #4
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 #5
Source File: SpecTestCase.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private void doFailWrite(JSONObject writeFailureSpec) throws Exception {
  JSONObject errorSpec = writeFailureSpec.getJSONObject("error");
  boolean keepInQueue = writeFailureSpec.optBoolean("keepInQueue", false);

  int code = errorSpec.getInt("code");
  Status error = Status.fromCodeValue(code);

  Pair<Mutation, Task<Void>> write = getCurrentOutstandingWrites().get(0);
  validateNextWriteSent(write.first);

  // If this is a permanent error, the write is not expected to be sent again.
  if (!keepInQueue) {
    getCurrentOutstandingWrites().remove(0);
  }

  log("      Failing a write.");
  queue.runSync(() -> datastore.failWrite(error));
}
 
Example #6
Source File: firebaseutils.java    From LuxVilla with Apache License 2.0 6 votes vote down vote up
public static void setuserfirstdata(final Context context, String username){
    FirebaseAuth auth=FirebaseAuth.getInstance();
    FirebaseUser user = auth.getCurrentUser();
    UserProfileChangeRequest.Builder builder = new UserProfileChangeRequest.Builder();
    builder.setDisplayName(username);
    if (user !=null){
        user.updateProfile(builder.build()).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (!task.isSuccessful()){
                    Toast.makeText(context,"Ocorreu um erro",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

}
 
Example #7
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 6 votes vote down vote up
public void signOut() {
  Log.d(TAG, "signOut()");

  mGoogleSignInClient.signOut().addOnCompleteListener(this,
      new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

          if (task.isSuccessful()) {
            Log.d(TAG, "signOut(): success");
          } else {
            handleException(task.getException(), "signOut() failed!");
          }

          onDisconnected();
        }
      });
}
 
Example #8
Source File: DriveServiceHelper.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Opens the file identified by {@code fileId} and returns a {@link Pair} of its name and
 * contents.
 */
public Task<Pair<String, String>> readFile(String fileId) {
    return Tasks.call(mExecutor, () -> {
            // Retrieve the metadata as a File object.
            File metadata = mDriveService.files().get(fileId).execute();
            String name = metadata.getName();

            // Stream the file contents to a String.
            try (InputStream is = mDriveService.files().get(fileId).executeMediaAsInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                StringBuilder stringBuilder = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                String contents = stringBuilder.toString();

                return Pair.create(name, contents);
            }
        });
}
 
Example #9
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void updateWithServerTimestamp() {
    // [START update_with_server_timestamp]
    DocumentReference docRef = db.collection("objects").document("some-id");

    // Update the timestamp field with the value from the server
    Map<String,Object> updates = new HashMap<>();
    updates.put("timestamp", FieldValue.serverTimestamp());

    docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
        // [START_EXCLUDE]
        @Override
        public void onComplete(@NonNull Task<Void> task) {}
        // [START_EXCLUDE]
    });
    // [END update_with_server_timestamp]
}
 
Example #10
Source File: OptimizePromotionsActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
private void initConfig() {
    // [START pred_optimize_promotions_init]
    mConfig = FirebaseRemoteConfig.getInstance();

    Map<String, Object> remoteConfigDefaults = new HashMap<>();
    remoteConfigDefaults.put("promoted_bundle", "basic");
    mConfig.setDefaultsAsync(remoteConfigDefaults)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        // Default value successfully set
                    } else {
                        // Failed to set default value
                    }
                }
            });
    // [END pred_optimize_promotions_init]
}
 
Example #11
Source File: DownloadTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void streamDownload() throws Exception {
  System.out.println("Starting test streamDownload.");

  MockConnectionFactory factory = NetworkLayerMock.ensureNetworkMock("streamDownload", true);
  final boolean[] completeHandlerInvoked = new boolean[] {false};

  Task<StreamDownloadResponse> task =
      TestDownloadHelper.streamDownload(
          bitmap -> {
            assertNotNull(bitmap);
            assertEquals(2560, bitmap.getWidth());
            assertEquals(1710, bitmap.getHeight());
            completeHandlerInvoked[0] = true;
          },
          null,
          "image.jpg",
          -1);

  TestUtil.await(task);

  factory.verifyOldMock();
  TestUtil.verifyTaskStateChanges("streamDownload", task.getResult());
  assertTrue(completeHandlerInvoked[0]);
}
 
Example #12
Source File: UploadTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyUpload() throws Exception {
  System.out.println("Starting test emptyUpload.");

  MockConnectionFactory factory = NetworkLayerMock.ensureNetworkMock("emptyUpload", true);

  String filename = TEST_ASSET_ROOT + "empty.dat";
  ClassLoader classLoader = UploadTest.class.getClassLoader();
  InputStream imageStream = classLoader.getResourceAsStream(filename);
  Uri sourceFile = Uri.parse("file://" + filename);

  ContentResolver resolver =
      RuntimeEnvironment.application.getApplicationContext().getContentResolver();
  Shadows.shadowOf(resolver).registerInputStream(sourceFile, imageStream);

  Task<StringBuilder> task = TestUploadHelper.fileUpload(sourceFile, "empty.dat");

  TestUtil.await(task, 5, TimeUnit.SECONDS);

  factory.verifyOldMock();
  TestUtil.verifyTaskStateChanges("emptyUpload", task.getResult().toString());
}
 
Example #13
Source File: Loginactivity.java    From LuxVilla with Apache License 2.0 6 votes vote down vote up
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    firebaseAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    // 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()) {
                        Snackbar.make(linearLayout,"Ocorreu um erro ao conectar", Snackbar.LENGTH_LONG).show();
                    } else {
                        startActivity(new Intent(Loginactivity.this, MainActivity.class));
                        finish();
                    }
                }
            });
}
 
Example #14
Source File: MainActivity.java    From android-basic-samples with Apache License 2.0 6 votes vote down vote up
private void signInSilently() {
  Log.d(TAG, "signInSilently()");

  mGoogleSignInClient.silentSignIn().addOnCompleteListener(this,
      new OnCompleteListener<GoogleSignInAccount>() {
        @Override
        public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
          if (task.isSuccessful()) {
            Log.d(TAG, "signInSilently(): success");
            onConnected(task.getResult());
          } else {
            Log.d(TAG, "signInSilently(): failure", task.getException());
            onDisconnected();
          }
        }
      });
}
 
Example #15
Source File: MainActivity.java    From wearable with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the data.  Since it specify a client, everyone who is listening to the path, will
 * get the data.
 */
private void sendData(String message) {
    PutDataMapRequest dataMap = PutDataMapRequest.create(datapath);
    dataMap.getDataMap().putString("message", message);
    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) {
                Log.d(TAG, "Sending message was successful: " + dataItem);
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "Sending message failed: " + e);
            }
        })
    ;
}
 
Example #16
Source File: AutoMLImageLabelerProcessor.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
@Override
protected Task<List<FirebaseVisionImageLabel>> detectInImage(final FirebaseVisionImage image) {
  if (modelDownloadingTask == null) {
    // No download task means only the locally bundled model is used. Model can be used directly.
    return detector.processImage(image);
  } else if (!modelDownloadingTask.isComplete()) {
    if (mode == Mode.LIVE_PREVIEW) {
      Log.i(TAG, "Model download is in progress. Skip detecting image.");
      return Tasks.forResult(Collections.<FirebaseVisionImageLabel>emptyList());
    } else {
      Log.i(TAG, "Model download is in progress. Waiting...");
      return modelDownloadingTask.continueWithTask(new Continuation<Void, Task<List<FirebaseVisionImageLabel>>>() {
        @Override
        public Task<List<FirebaseVisionImageLabel>> then(@NonNull Task<Void> task) {
          return processImageOnDownloadComplete(image);
        }
      });
    }
  } else {
    return processImageOnDownloadComplete(image);
  }
}
 
Example #17
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 #18
Source File: FirebaseSegmentation.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@NonNull
public synchronized Task<Void> setCustomInstallationId(@Nullable String customInstallationId) {
  if (customInstallationId == null) {
    return Tasks.call(executor, () -> clearCustomInstallationId());
  }
  return Tasks.call(executor, () -> updateCustomInstallationId(customInstallationId));
}
 
Example #19
Source File: TestUploadHelper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public static Task<Void> fileUploadQueuedCancel(
    final StringBuilder builder, final Uri sourcefile) {
  TaskCompletionSource<Void> result = new TaskCompletionSource<>();

  final StorageReference storage = FirebaseStorage.getInstance().getReference("image.jpg");
  StorageMetadata metadata =
      new StorageMetadata.Builder()
          .setContentType("text/plain")
          .setCustomMetadata("myData", "myFoo")
          .build();

  ControllableSchedulerHelper.getInstance().pause();
  final UploadTask task = storage.putFile(sourcefile, metadata);
  final Semaphore semaphore = new Semaphore(0);
  attachListeners(
      builder,
      task,
      null,
      null,
      null,
      null,
      null,
      completedTask -> {
        ControllableSchedulerHelper.getInstance().verifyCallbackThread();
        String statusMessage = "\nonComplete:Success=\n" + completedTask.isSuccessful();
        Log.i(TAG, statusMessage);
        builder.append(statusMessage);
        result.setResult(null);
      });

  // cancel while the task is still queued.
  task.cancel();

  ControllableSchedulerHelper.getInstance().resume();

  return result.getTask();
}
 
Example #20
Source File: StitchAppClientImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <ResultT> Task<ResultT> callFunction(
    final String name,
    final List<?> args,
    final Decoder<ResultT> resultDecoder) {
  return dispatcher.dispatchTask(
      new Callable<ResultT>() {
        @Override
        public ResultT call() {
          return coreClient.callFunction(name, args, null, resultDecoder);
        }
      });
}
 
Example #21
Source File: FirebaseRemoteConfigTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void fetch_hasNoErrors_taskReturnsSuccess() {
  when(mockFetchHandler.fetch()).thenReturn(Tasks.forResult(firstFetchedContainerResponse));

  Task<Void> fetchTask = frc.fetch();

  assertWithMessage("Fetch failed!").that(fetchTask.isSuccessful()).isTrue();
}
 
Example #22
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 #23
Source File: FirebaseAuthRxWrapper.java    From outlay with Apache License 2.0 5 votes vote down vote up
public Observable<AuthResult> signInAnonymously() {
    return Observable.create(subscriber -> {
        Task<AuthResult> task = firebaseAuth.signInAnonymously();
        task.addOnCompleteListener(resultTask -> {
            if (task.isSuccessful()) {
                AuthResult authResult = task.getResult();
                subscriber.onNext(authResult);
                subscriber.onCompleted();
            } else {
                Exception e = task.getException();
                subscriber.onError(e);
            }
        });
    });
}
 
Example #24
Source File: StitchAuthImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Task<Void> removeUser() {
  return dispatcher.dispatchTask(
      new Callable<Void>() {
        @Override
        public Void call() {
          removeUserInternal();
          return null;
        }
      });
}
 
Example #25
Source File: ProfileInteractor.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void addRegistrationToken(String token, String userId) {
    Task<Void> task = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.PROFILES_DB_KEY)
            .child(userId).child("notificationTokens")
            .child(token).setValue(true);
    task.addOnCompleteListener(task1 -> LogUtil.logDebug(TAG, "addRegistrationToken, success: " + task1.isSuccessful()));
}
 
Example #26
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void linkWithSignInLink(String email, String emailLink) {
    FirebaseAuth auth = FirebaseAuth.getInstance();
    
    // [START auth_link_with_link]
    // Construct the email link credential from the current URL.
    AuthCredential credential =
            EmailAuthProvider.getCredentialWithLink(email, emailLink);

    // Link the credential to the current user.
    auth.getCurrentUser().linkWithCredential(credential)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "Successfully linked emailLink credential!");
                        AuthResult result = task.getResult();
                        // You can access the new user via result.getUser()
                        // Additional user info profile *not* available via:
                        // result.getAdditionalUserInfo().getProfile() == null
                        // You can check if the user is new or existing:
                        // result.getAdditionalUserInfo().isNewUser()
                    } else {
                        Log.e(TAG, "Error linking emailLink credential", task.getException());
                    }
                }
            });
    // [END auth_link_with_link]
}
 
Example #27
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void buildShortSuffix() {
    // [START ddl_short_suffix]
    Task<ShortDynamicLink> shortLinkTask = FirebaseDynamicLinks.getInstance().createDynamicLink()
            // ...
            .buildShortDynamicLink(ShortDynamicLink.Suffix.SHORT);
            // ...
    // [END ddl_short_suffix]
}
 
Example #28
Source File: AutoCompleteTask.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public Task<TResult> addOnSuccessListener(@NonNull OnSuccessListener<? super TResult> onSuccessListener) {
    if (mSuccess) {
        onSuccessListener.onSuccess(mResult);
    }
    return this;
}
 
Example #29
Source File: SignInController.java    From PGSGP with MIT License 5 votes vote down vote up
public void signOut(GoogleSignInClient googleSignInClient) {
    googleSignInClient.signOut().addOnCompleteListener(activity, new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                godotCallbacksUtils.invokeGodotCallback(GodotCallbacksUtils.SIGN_OUT_SUCCESS, new Object[]{});
            } else {
                godotCallbacksUtils.invokeGodotCallback(GodotCallbacksUtils.SIGN_OUT_FAILED, new Object[]{});
            }
        }
    });
}
 
Example #30
Source File: RemoteMongoIterableImpl.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <A extends Collection<? super ResultT>> Task<A> into(final A target) {
  return dispatcher.dispatchTask(new Callable<A>() {
    @Override
    public A call() {
      return proxy.into(target);
    }
  });
}