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 |
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 |
@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: Loginactivity.java From LuxVilla with Apache License 2.0 | 6 votes |
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 #4
Source File: TransactionTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@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 |
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: FCMRegistration.java From Android-SDK with MIT License | 6 votes |
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 #7
Source File: firebaseutils.java From LuxVilla with Apache License 2.0 | 6 votes |
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 #8
Source File: SkeletonActivity.java From android-basic-samples with Apache License 2.0 | 6 votes |
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 #9
Source File: TransactionTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@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 #10
Source File: AutoMLImageLabelerProcessor.java From quickstart-android with Apache License 2.0 | 6 votes |
@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 #11
Source File: DriveServiceHelper.java From android-samples with Apache License 2.0 | 6 votes |
/** * 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 #12
Source File: DocSnippets.java From snippets-android with Apache License 2.0 | 6 votes |
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 #13
Source File: OptimizePromotionsActivity.java From snippets-android with Apache License 2.0 | 6 votes |
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 #14
Source File: MainActivity.java From wearable with Apache License 2.0 | 6 votes |
/** * 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 #15
Source File: MainActivity.java From android-basic-samples with Apache License 2.0 | 6 votes |
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 #16
Source File: DownloadTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@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 #17
Source File: UploadTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@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 #18
Source File: TestUploadHelper.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
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 #19
Source File: RemoteMongoCursorImpl.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Override public Task<Boolean> hasNext() { return dispatcher.dispatchTask(new Callable<Boolean>() { @Override public Boolean call() { return proxy.hasNext(); } }); }
Example #20
Source File: FirestackAuth.java From react-native-firestack with MIT License | 5 votes |
@ReactMethod public void updateUserEmail(final String email, final Callback callback) { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { user.updateEmail(email) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User email address updated"); FirebaseUser u = FirebaseAuth.getInstance().getCurrentUser(); userCallback(u, callback); } else { // userErrorCallback(task, callback); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception ex) { userExceptionCallback(ex, callback); } }); } else { WritableMap err = Arguments.createMap(); err.putInt("errorCode", NO_CURRENT_USER); err.putString("errorMessage", "No current user"); callback.invoke(err); } }
Example #21
Source File: SolutionArrays.java From snippets-android with Apache License 2.0 | 5 votes |
public void queryForCats() { // [START query_for_cats] db.collection("posts") .whereEqualTo("categories.cats", true) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { // [START_EXCLUDE] @Override public void onComplete(@NonNull Task<QuerySnapshot> task) {} // [END_EXCLUDE] }); // [END query_for_cats] }
Example #22
Source File: MainActivity.java From android-samples with Apache License 2.0 | 5 votes |
private Task<Void> loadFolderContents(DriveFolder folder) { Query folderQuery = new Query.Builder() .setSortOrder(new SortOrder.Builder() .addSortAscending(SortableField.CREATED_DATE) .build()) .build(); Task<MetadataBuffer> task = mDriveResourceClient.queryChildren(folder, folderQuery); return task.continueWith(task1 -> { MetadataBuffer items = task1.getResult(); List<Metadata> children = new ArrayList<>(items.getCount()); try { for (int i = 0; i < items.getCount(); i++) { children.add(items.get(i).freeze()); } // Show folders first Collections.sort(children, new Comparator<Metadata>() { @Override public int compare(Metadata a, Metadata b) { int aVal = a.isFolder() ? 1 : 0; int bVal = b.isFolder() ? 1 : 0; return bVal - aVal; } }); mFileFolderAdapter.setFiles(children); mFileFolderAdapter.notifyDataSetChanged(); } finally { items.release(); } return null; }); }
Example #23
Source File: UploadTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Test public void fileUploadWithPauseCancel() throws Exception { System.out.println("Starting test fileUploadWithPauseCancel."); ResumableUploadCancelRequest.cancelCalled = false; MockConnectionFactory factory = NetworkLayerMock.ensureNetworkMock("fileUploadWithPauseCancel", true); factory.setPauseRecord(4); String filename = TEST_ASSET_ROOT + "image.jpg"; 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.fileUploadWithPauseCancel(factory.getSemaphore(), sourceFile); // This is 20 seconds due to a fairness bug where resumed tasks can be put at the end. TestUtil.await(task, 20, TimeUnit.SECONDS); TestUtil.verifyTaskStateChanges("fileUploadWithPauseCancel", task.getResult().toString()); Assert.assertTrue(ResumableUploadCancelRequest.cancelCalled); }
Example #24
Source File: FirebaseRemoteConfigTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Test public void ensureInitialized_notInitialized_isNotComplete() { loadCacheWithConfig(mockFetchedCache, /*container=*/ null); loadCacheWithConfig(mockDefaultsCache, /*container=*/ null); loadActivatedCacheWithIncompleteTask(); loadInstanceIdAndToken(); Task<FirebaseRemoteConfigInfo> initStatus = frc.ensureInitialized(); assertWithMessage("FRC is initialized even though activated configs have not loaded!") .that(initStatus.isComplete()) .isFalse(); }
Example #25
Source File: TodoListActivity.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
private Task<List<TodoItem>> getItemsWithRegexFilter(final String regex) { return items.sync().find( new Document( TodoItem.Fields.TASK, new Document().append("$regex", new BsonRegularExpression(regex)).append("$options", "i"))) .into(new ArrayList<>()); }
Example #26
Source File: StorageReference.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
/** * 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 #27
Source File: MainActivity.java From quickstart-android with Apache License 2.0 | 5 votes |
private void onAddMessageClicked() { String inputMessage = binding.fieldMessageInput.getText().toString(); if (TextUtils.isEmpty(inputMessage)) { showSnackbar("Please enter a message."); return; } // [START call_add_message] addMessage(inputMessage) .addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { if (!task.isSuccessful()) { Exception e = task.getException(); if (e instanceof FirebaseFunctionsException) { FirebaseFunctionsException ffe = (FirebaseFunctionsException) e; FirebaseFunctionsException.Code code = ffe.getCode(); Object details = ffe.getDetails(); } // [START_EXCLUDE] Log.w(TAG, "addMessage:onFailure", e); showSnackbar("An error occurred."); return; // [END_EXCLUDE] } // [START_EXCLUDE] String result = task.getResult(); binding.fieldMessageOutput.setText(result); // [END_EXCLUDE] } }); // [END call_add_message] }
Example #28
Source File: RxFirebaseUser.java From rxfirebase with Apache License 2.0 | 5 votes |
/** * @param user * @param email * @return */ @CheckReturnValue @NonNull public static Completable updateEmail( @NonNull final FirebaseUser user, @NonNull final String email) { return RxTask.completes(new Callable<Task<Void>>() { @Override public Task<Void> call() throws Exception { return user.updateEmail(email); } }); }
Example #29
Source File: StitchAppClientImpl.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Override public <ResultT> Task<ResultT> callFunction( final String name, final List<?> args, final Class<ResultT> resultClass, final CodecRegistry codecRegistry ) { return dispatcher.dispatchTask( new Callable<ResultT>() { @Override public ResultT call() { return coreClient.callFunction(name, args, null, resultClass, codecRegistry); } }); }
Example #30
Source File: SourceTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Test public void getNonExistingCollectionWhileOfflineWithSourceEqualToServer() { CollectionReference colRef = testCollection(); waitFor(colRef.getFirestore().disableNetwork()); Task<QuerySnapshot> qrySnapTask = colRef.get(Source.SERVER); waitForException(qrySnapTask); }