Java Code Examples for com.google.android.gms.tasks.OnFailureListener

The following examples show how to use com.google.android.gms.tasks.OnFailureListener. These examples are extracted from open source projects. 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 Project: react-native-fitness   Source File: Manager.java    License: MIT License 8 votes vote down vote up
public void subscribeToSteps(Context context, final Promise promise){
    final GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(context);
    if(account == null){
        promise.resolve(false);
        return;
    }
    Fitness.getRecordingClient(context, account)
            .subscribe(DataType.TYPE_STEP_COUNT_DELTA)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    promise.resolve(true);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    promise.resolve(false);
                }
            });
}
 
Example 2
Source Project: connectivity-samples   Source File: ConnectionsActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends a connection request to the endpoint. Either {@link #onConnectionInitiated(Endpoint,
 * ConnectionInfo)} or {@link #onConnectionFailed(Endpoint)} will be called once we've found out
 * if we successfully reached the device.
 */
protected void connectToEndpoint(final Endpoint endpoint) {
  logV("Sending a connection request to endpoint " + endpoint);
  // Mark ourselves as connecting so we don't connect multiple times
  mIsConnecting = true;

  // Ask to connect
  mConnectionsClient
      .requestConnection(getName(), endpoint.getId(), mConnectionLifecycleCallback)
      .addOnFailureListener(
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              logW("requestConnection() failed.", e);
              mIsConnecting = false;
              onConnectionFailed(endpoint);
            }
          });
}
 
Example 3
@Override
public void handleEvent(final MethodChannel.Result result) {
    FirebaseTranslateModelManager.getInstance().getAvailableModels(FirebaseApp.getInstance())
            .addOnSuccessListener(new OnSuccessListener<Set<FirebaseTranslateRemoteModel>>() {
                @Override
                public void onSuccess(Set<FirebaseTranslateRemoteModel> models) {
                    List<Map<String, Object>> translateModels = new ArrayList<>(models.size());
                    for (FirebaseTranslateRemoteModel model : models) {
                        Map<String, Object> langData = new HashMap<>();
                        langData.put("languageCode", model.getLanguageCode());
                        translateModels.add(langData);
                    }
                    result.success(translateModels);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    result.error("viewError", e.getLocalizedMessage(), null);
                }
            });
}
 
Example 4
@Override
public void handleEvent(String modelName, final MethodChannel.Result result) {
    FirebaseTranslateRemoteModel model =
            new FirebaseTranslateRemoteModel.Builder(FirebaseTranslateLanguage.languageForLanguageCode(modelName)).build();
    FirebaseTranslateModelManager.getInstance().deleteDownloadedModel(model)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void v) {
                    result.success("Deleted");
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    result.error("deleteError", e.getLocalizedMessage(), null);
                }
            });
}
 
Example 5
@Override
public void handleEvent(String modelName, final MethodChannel.Result result) {
    Integer languageCode = FirebaseTranslateLanguage.languageForLanguageCode(modelName);
    FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder().build();
    FirebaseTranslateRemoteModel model = new FirebaseTranslateRemoteModel.Builder(languageCode)
            .setDownloadConditions(conditions)
            .build();
    FirebaseTranslateModelManager.getInstance().downloadRemoteModelIfNeeded(model)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void v) {
                    result.success("Downloaded");
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    result.error("downloadError", e.getLocalizedMessage(), null);
                }
            });
}
 
Example 6
Source Project: aircon   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
private void loadFireBaseConfig() {
	FirebaseRemoteConfig.getInstance()
	                    .fetch(0)
	                    .addOnSuccessListener(new OnSuccessListener<Void>() {
		                    @Override
		                    public void onSuccess(final Void aVoid) {
			                    FirebaseRemoteConfig.getInstance()
			                                        .activate();
			                    Log.i(App.TAG, "Firebase config loaded");
			                    onFireBaseConfigLoaded();
		                    }
	                    })
	                    .addOnFailureListener(new OnFailureListener() {
		                    @Override
		                    public void onFailure(@NonNull final Exception e) {
			                    Log.e(App.TAG, "Failed to load firebase config: " + e);
			                    onFireBaseConfigLoaded();
		                    }
	                    });
}
 
Example 7
private void detectInVisionImage( FirebaseVisionImage image) {
    detector.processImage(image)
    .addOnSuccessListener(
        new OnSuccessListener<FirebaseVisionText>() {
            // Note: StringBuilder is MUCH MUCH FASTER THAN Strings
            @Override
            public void onSuccess(FirebaseVisionText results) {
               textBlocks = results.getTextBlocks();
               StringBuilder builder = new StringBuilder();
               for (int i = 0; i < textBlocks.size(); i++) {
                   builder.append(textBlocks.get(i).getText());
                }
             allText = builder.toString();
            Log.d(TAG,"Bitmap Success read: "+allText);
            allText = filterCaptcha(allText);
            listener.onCaptchaUpdate(allText);
        }
    })
    .addOnFailureListener(
        new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Bitmap Text detection failed." + e);
            }
        });
}
 
Example 8
Source Project: Hify   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
private void updateToken() {

        final String token_id = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, MODE_PRIVATE).getString("regId","");
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token_ids", FieldValue.arrayUnion(token_id));

        if(isOnline()) {

            firestore.collection("Users").document(currentuser.getUid()).update(tokenMap)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Log.d("TOKEN", token_id);
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.d("Error Token", e.getMessage());
                        }
                    });

        }
    }
 
Example 9
Source Project: Hify   Source File: NotificationActivity.java    License: MIT License 6 votes vote down vote up
private void updateReadStatus() {

        String read=getIntent().getStringExtra("read");
        if(read.equals("false")){
            Map<String,Object> readMap=new HashMap<>();
            readMap.put("read","true");

            mFirestore.collection("Users").document(current_id).collection("Notifications")
                    .document(getIntent().getStringExtra("doc_id")).update(readMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.i("done","read:true");
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.i("error","read:false::"+e.getLocalizedMessage());
                }
            });
        }

    }
 
Example 10
Source Project: Hify   Source File: NotificationReplyActivity.java    License: MIT License 6 votes vote down vote up
private void updateReadStatus() {

        String read=getIntent().getStringExtra("read");
        if(read=="false"){
            Map<String,Object> readMap=new HashMap<>();
            readMap.put("read","true");

            mFirestore.collection("Users").document(current_id).collection("Notifications_reply")
                    .document(getIntent().getStringExtra("doc_id")).update(readMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.i("done","read:true");
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.i("error","read:false::"+e.getLocalizedMessage());
                }
            });
        }

    }
 
Example 11
Source Project: Hify   Source File: NotificationImage.java    License: MIT License 6 votes vote down vote up
private void updateReadStatus() {

        String read=getIntent().getStringExtra("read");
        if(read=="false"){
            Map<String,Object> readMap=new HashMap<>();
            readMap.put("read","true");

            mFirestore.collection("Users").document(current_id).collection("Notifications_image")
                    .document(getIntent().getStringExtra("doc_id")).update(readMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.i("done","read:true");
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.i("error","read:false::"+e.getLocalizedMessage());
                }
            });
        }

    }
 
Example 12
Source Project: Hify   Source File: NotificationImageReply.java    License: MIT License 6 votes vote down vote up
private void updateReadStatus() {

        String read=getIntent().getStringExtra("read");
        if(read=="false"){
            Map<String,Object> readMap=new HashMap<>();
            readMap.put("read","true");

            mFirestore.collection("Users").document(current_id).collection("Notifications_reply_image")
                    .document(getIntent().getStringExtra("doc_id")).update(readMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.i("done","read:true");
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.i("error","read:false::"+e.getLocalizedMessage());
                }
            });
        }

    }
 
Example 13
Source Project: SnapchatClone   Source File: ProfileActivity.java    License: MIT License 6 votes vote down vote up
private void saveProfileImage() {
    if (newProfileImageUrl != null) {
        if (!currentProfileImageUrl.equals("default")) {
            StorageReference photoDelete = FirebaseStorage.getInstance().getReferenceFromUrl(currentProfileImageUrl);

            photoDelete.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    uploadImage();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    saveProfileImage();
                }
            });
        } else {
            uploadImage();
        }
    } else {
        saveProfile();
    }
}
 
Example 14
Source Project: ridesharing-android   Source File: DriverMapPresenter.java    License: MIT License 6 votes vote down vote up
public void endRide() {
    if (mState.getOrder() != null) {
        mView.showProgressBar();

        DocumentReference washingtonRef = db.collection("orders").document(mState.getOrder().id);
        washingtonRef
                .update("status", Order.COMPLETED)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        mView.hideProgressBar();
                        Log.d(TAG, "DocumentSnapshot successfully updated!");
                        trackingPresenter.adjustTrackingState();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        mView.hideProgressBar();
                        Log.w(TAG, "Error updating document", e);
                    }
                });
    }
}
 
Example 15
@ReactMethod
public void rejectConnection(final String serviceId, final String endpointId) {
	final Endpoint endpoint = mEndpoints.get(serviceId+"_"+endpointId);

	logV("rejecting connection from " + endpointId);
	final ConnectionsClient clientSingleton = getConnectionsClientSingleton(serviceId);

	clientSingleton
		.rejectConnection(endpointId)
		.addOnFailureListener(
			new OnFailureListener() {
				@Override
				public void onFailure(@NonNull Exception e) {
					ApiException apiException = (ApiException) e;

					logW("rejectConnection() failed.", e);
				}
			});
}
 
Example 16
/**
 * Sends a {@link Payload} to all currently connected endpoints.
 *
 * @param payload The data you want to send.
 */
protected void sendPayload(final String serviceId, final String endpointId, final Payload payload) {
	final ConnectionsClient clientSingleton = getConnectionsClientSingleton(serviceId);

	clientSingleton
		.sendPayload(endpointId, payload)
		.addOnFailureListener(
			new OnFailureListener() {
				@Override
				public void onFailure(@NonNull Exception e) {
					ApiException apiException = (ApiException) e;

					logW("sendPayload() failed.", e);

					onSendPayloadFailed(serviceId, endpointId, payload, apiException.getStatusCode());
				}
			});
}
 
Example 17
Source Project: Android-9-Development-Cookbook   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        GeofencingClient geofencingClient = LocationServices.getGeofencingClient(this);
        geofencingClient.addGeofences(createGeofencingRequest(), createGeofencePendingIntent())
                .addOnSuccessListener(this, new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(MainActivity.this, "onSuccess()", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MainActivity.this,
                                "onFailure(): " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    } else {
        ActivityCompat.requestPermissions(this,
                new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION},1);
    }
}
 
Example 18
Source Project: Android-9-Development-Cookbook   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onStop() {
    super.onStop();

    GeofencingClient geofencingClient = LocationServices.getGeofencingClient(this);
    geofencingClient.removeGeofences(createGeofencePendingIntent())
            .addOnSuccessListener(this, new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    //Success
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    //Failure
                }
            });
}
 
Example 19
Source Project: react-native-fitness   Source File: Manager.java    License: MIT License 6 votes vote down vote up
public void subscribeToActivity(Context context, final Promise promise){
    final GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(context);
    if(account == null){
        promise.resolve(false);
        return;
    }
    Fitness.getRecordingClient(context, account)
            .subscribe(DataType.TYPE_ACTIVITY_SAMPLES)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    promise.resolve(true);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    promise.resolve(false);
                }
            });

}
 
Example 20
Source Project: GoogleFaceDetectDemo   Source File: PictureActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
    faceDetector.detectInImage(image).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace>>() {
        @Override
        public void onSuccess(List<FirebaseVisionFace> firebaseVisionFaces) {
            faceview.setContent(bitmap, firebaseVisionFaces);
            FirebaseVisionFace face = firebaseVisionFaces.get(0);
            float leftEyeOpenProbability = face.getLeftEyeOpenProbability();
            float rightEyeOpenProbability = face.getRightEyeOpenProbability();
            float smilingProbability = face.getSmilingProbability();

            mFaceBound.setText("Face Bound:  " + "--" + face.getBoundingBox().left + "--" + face.getBoundingBox().top
                    + "--" + face.getBoundingBox().right + "--" + face.getBoundingBox().bottom);
            mEyeLevel.setText("Eye Open Possible:  " + "leftEyeOpenProbability=" + leftEyeOpenProbability +
                    "--rightEyeOpenProbability=" + rightEyeOpenProbability);
            mSmileLevel.setText("Smile Possible:  " + "smilingProbability=" + smilingProbability);

        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {

        }
    });
}
 
Example 21
Source Project: fast_qr_reader_view   Source File: VisionProcessorBase.java    License: MIT License 6 votes vote down vote up
private void detectInVisionImage(
            FirebaseVisionImage image,
            final FrameMetadata metadata) {//,
//            final GraphicOverlay graphicOverlay) {
        detectInImage(image)
                .addOnSuccessListener(
                        new OnSuccessListener<T>() {
                            @Override
                            public void onSuccess(T results) {
                                shouldThrottle.set(false);
                                VisionProcessorBase.this.onSuccess(results, metadata);//,
                                //graphicOverlay);
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                shouldThrottle.set(false);
                                VisionProcessorBase.this.onFailure(e);
                            }
                        });
        // Begin throttling until this frame of input has been processed, either in onSuccess or
        // onFailure.
        shouldThrottle.set(true);
    }
 
Example 22
Source Project: play_games   Source File: PlayGamesPlugin.java    License: MIT License 6 votes vote down vote up
private void signOut() {
    GoogleSignInOptions.Builder builder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
    GoogleSignInOptions opts = builder.build();
    GoogleSignInClient signInClient = GoogleSignIn.getClient(registrar.activity(), opts);
    signInClient.signOut().addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            currentAccount = null;
            Map<String, Object> successMap = new HashMap<>();
            successMap.put("type", "SUCCESS");
            result(successMap);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            error("ERROR_SIGN_OUT", e);
            Log.i(TAG, "Failed to signout", e);
        }
    });

}
 
Example 23
Source Project: ridesharing-android   Source File: DriverMapPresenter.java    License: MIT License 6 votes vote down vote up
public void startRide() {
    if (mState.getOrder() != null) {
        mView.showProgressBar();

        DocumentReference washingtonRef = db.collection("orders").document(mState.getOrder().id);
        washingtonRef
                .update("status", Order.STARTED_RIDE)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        mView.hideProgressBar();
                        Log.d(TAG, "DocumentSnapshot successfully updated!");
                        trackingPresenter.adjustTrackingState();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        mView.hideProgressBar();
                        Log.w(TAG, "Error updating document", e);
                    }
                });
    }
}
 
Example 24
Source Project: capacitor-firebase-auth   Source File: CapacitorFirebaseAuth.java    License: MIT License 5 votes vote down vote up
private void nativeAuth(final PluginCall savedCall, final AuthCredential credential) {
    this.firebaseAuth.signInWithCredential(credential)
            .addOnCompleteListener(this.getActivity(), new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(PLUGIN_TAG, "Firebase Sign In with Credential succeed.");
                        FirebaseUser user = firebaseAuth.getCurrentUser();

                        if (user == null) {
                            Log.w(PLUGIN_TAG, "Ops, no Firebase user after Sign In with Credential succeed.");
                            savedCall.reject("Ops, no Firebase user after Sign In with Credential succeed");
                        } else {
                            JSObject jsResult = build(credential, savedCall);
                            savedCall.success(jsResult);
                        }
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(PLUGIN_TAG, "Firebase Sign In with Credential failure.", task.getException());
                        savedCall.reject("Firebase Sign In with Credential failure.");
                    }
                }
            }).addOnFailureListener(this.getActivity(), new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception ex) {
                    // If sign in fails, display a message to the user.
                    Log.w(PLUGIN_TAG, "Firebase Sign In with Credential failure.", ex);
                    savedCall.reject("Firebase Sign In with Credential failure.");

                }
    });
}
 
Example 25
Source Project: connectivity-samples   Source File: ConnectionsActivity.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the device to advertising mode. It will broadcast to other devices in discovery mode.
 * Either {@link #onAdvertisingStarted()} or {@link #onAdvertisingFailed()} will be called once
 * we've found out if we successfully entered this mode.
 */
protected void startAdvertising() {
  mIsAdvertising = true;
  final String localEndpointName = getName();

  AdvertisingOptions.Builder advertisingOptions = new AdvertisingOptions.Builder();
  advertisingOptions.setStrategy(getStrategy());

  mConnectionsClient
      .startAdvertising(
          localEndpointName,
          getServiceId(),
          mConnectionLifecycleCallback,
          advertisingOptions.build())
      .addOnSuccessListener(
          new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void unusedResult) {
              logV("Now advertising endpoint " + localEndpointName);
              onAdvertisingStarted();
            }
          })
      .addOnFailureListener(
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              mIsAdvertising = false;
              logW("startAdvertising() failed.", e);
              onAdvertisingFailed();
            }
          });
}
 
Example 26
Source Project: connectivity-samples   Source File: ConnectionsActivity.java    License: Apache License 2.0 5 votes vote down vote up
/** Accepts a connection request. */
protected void acceptConnection(final Endpoint endpoint) {
  mConnectionsClient
      .acceptConnection(endpoint.getId(), mPayloadCallback)
      .addOnFailureListener(
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              logW("acceptConnection() failed.", e);
            }
          });
}
 
Example 27
Source Project: connectivity-samples   Source File: ConnectionsActivity.java    License: Apache License 2.0 5 votes vote down vote up
/** Rejects a connection request. */
protected void rejectConnection(Endpoint endpoint) {
  mConnectionsClient
      .rejectConnection(endpoint.getId())
      .addOnFailureListener(
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              logW("rejectConnection() failed.", e);
            }
          });
}
 
Example 28
Source Project: connectivity-samples   Source File: ConnectionsActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void send(Payload payload, Set<String> endpoints) {
  mConnectionsClient
      .sendPayload(new ArrayList<>(endpoints), payload)
      .addOnFailureListener(
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              logW("sendPayload() failed.", e);
            }
          });
}
 
Example 29
@Override
public void handleEvent(String text, Map<String, Object> options, final MethodChannel.Result result) {

    if (identifier != null && !options.equals(lastOptions)){
        identifier.close();
        identifier = null;
        lastOptions = null;
    }

    if (identifier == null){
        lastOptions = options;
        identifier = FirebaseNaturalLanguage.getInstance().getLanguageIdentification(parseOptions(lastOptions));
    }

    identifier.identifyPossibleLanguages(text)
            .addOnSuccessListener(
                    new OnSuccessListener<List<IdentifiedLanguage>>() {
                        @Override
                        public void onSuccess(List<IdentifiedLanguage> identifiedLanguages) {
                            List<Map<String, Object>> labels = new ArrayList<>(identifiedLanguages.size());
                            for (IdentifiedLanguage identifiedLanguage : identifiedLanguages) {
                                Map<String, Object> labelData = new HashMap<>();
                                String language = identifiedLanguage.getLanguageCode();
                                float confidence = identifiedLanguage.getConfidence();
                                labelData.put("confidence", (double) confidence);
                                labelData.put("languageCode", language);
                                labels.add(labelData);
                            }
                            result.success(labels);
                        }
                    })
            .addOnFailureListener(
                    new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            result.error("languageIdentifierError", e.getLocalizedMessage(), null);
                        }
                    });

}
 
Example 30
Source Project: LocationPicker   Source File: LocationPickerActivity.java    License: MIT License 5 votes vote down vote up
private void startLocationUpdates() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(LocationPickerActivity.this, "Location not Available", Toast.LENGTH_SHORT).show();
            return;
        }

        fusedLocationProviderClient.requestLocationUpdates(locationRequest,
                locationCallback,
                null /* Looper */)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d(TAG, "startLocationUpdates: onSuccess: ");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        if (e instanceof ApiException) {
                            Log.d(TAG, "startLocationUpdates: " + ((ApiException) e).getMessage());
                        } else {
                            Log.d(TAG, "startLocationUpdates: " + e.getMessage());
                        }
                    }
                });

    }