Search in sources :

Example 36 with OnSuccessListener

use of com.google.android.gms.tasks.OnSuccessListener in project android-play-location by googlesamples.

the class MainActivity method startLocationUpdates.

/**
 * Requests location updates from the FusedLocationApi. Note: we don't call this unless location
 * runtime permission has been granted.
 */
private void startLocationUpdates() {
    // Begin by checking if the device has the necessary location settings.
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest).addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {

        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            Log.i(TAG, "All location settings are satisfied.");
            // noinspection MissingPermission
            mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
            updateUI();
        }
    }).addOnFailureListener(this, new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception e) {
            int statusCode = ((ApiException) e).getStatusCode();
            switch(statusCode) {
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " + "location settings ");
                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the
                        // result in onActivityResult().
                        ResolvableApiException rae = (ResolvableApiException) e;
                        rae.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException sie) {
                        Log.i(TAG, "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    String errorMessage = "Location settings are inadequate, and cannot be " + "fixed here. Fix in Settings.";
                    Log.e(TAG, errorMessage);
                    Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                    mRequestingLocationUpdates = false;
            }
            updateUI();
        }
    });
}
Also used : ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) LocationSettingsResponse(com.google.android.gms.location.LocationSettingsResponse) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) ApiException(com.google.android.gms.common.api.ApiException)

Example 37 with OnSuccessListener

use of com.google.android.gms.tasks.OnSuccessListener in project PhotoBlog-Android-Blog-App by akshayejh.

the class NewPostActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_post);
    storageReference = FirebaseStorage.getInstance().getReference();
    firebaseFirestore = FirebaseFirestore.getInstance();
    firebaseAuth = FirebaseAuth.getInstance();
    current_user_id = firebaseAuth.getCurrentUser().getUid();
    newPostToolbar = findViewById(R.id.new_post_toolbar);
    setSupportActionBar(newPostToolbar);
    getSupportActionBar().setTitle("Add New Post");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    newPostImage = findViewById(R.id.new_post_image);
    newPostDesc = findViewById(R.id.new_post_desc);
    newPostBtn = findViewById(R.id.post_btn);
    newPostProgress = findViewById(R.id.new_post_progress);
    newPostImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setMinCropResultSize(512, 512).setAspectRatio(1, 1).start(NewPostActivity.this);
        }
    });
    newPostBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            final String desc = newPostDesc.getText().toString();
            if (!TextUtils.isEmpty(desc) && postImageUri != null) {
                newPostProgress.setVisibility(View.VISIBLE);
                final String randomName = UUID.randomUUID().toString();
                // PHOTO UPLOAD
                File newImageFile = new File(postImageUri.getPath());
                try {
                    compressedImageFile = new Compressor(NewPostActivity.this).setMaxHeight(720).setMaxWidth(720).setQuality(50).compressToBitmap(newImageFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageData = baos.toByteArray();
                // PHOTO UPLOAD
                UploadTask filePath = storageReference.child("post_images").child(randomName + ".jpg").putBytes(imageData);
                filePath.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                    @Override
                    public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {
                        final String downloadUri = task.getResult().getDownloadUrl().toString();
                        if (task.isSuccessful()) {
                            File newThumbFile = new File(postImageUri.getPath());
                            try {
                                compressedImageFile = new Compressor(NewPostActivity.this).setMaxHeight(100).setMaxWidth(100).setQuality(1).compressToBitmap(newThumbFile);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                            byte[] thumbData = baos.toByteArray();
                            UploadTask uploadTask = storageReference.child("post_images/thumbs").child(randomName + ".jpg").putBytes(thumbData);
                            uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                                @Override
                                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                    String downloadthumbUri = taskSnapshot.getDownloadUrl().toString();
                                    Map<String, Object> postMap = new HashMap<>();
                                    postMap.put("image_url", downloadUri);
                                    postMap.put("image_thumb", downloadthumbUri);
                                    postMap.put("desc", desc);
                                    postMap.put("user_id", current_user_id);
                                    postMap.put("timestamp", FieldValue.serverTimestamp());
                                    firebaseFirestore.collection("Posts").add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {

                                        @Override
                                        public void onComplete(@NonNull Task<DocumentReference> task) {
                                            if (task.isSuccessful()) {
                                                Toast.makeText(NewPostActivity.this, "Post was added", Toast.LENGTH_LONG).show();
                                                Intent mainIntent = new Intent(NewPostActivity.this, MainActivity.class);
                                                startActivity(mainIntent);
                                                finish();
                                            } else {
                                            }
                                            newPostProgress.setVisibility(View.INVISIBLE);
                                        }
                                    });
                                }
                            }).addOnFailureListener(new OnFailureListener() {

                                @Override
                                public void onFailure(@NonNull Exception e) {
                                // Error handling
                                }
                            });
                        } else {
                            newPostProgress.setVisibility(View.INVISIBLE);
                        }
                    }
                });
            }
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) HashMap(java.util.HashMap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) DocumentReference(com.google.firebase.firestore.DocumentReference) Compressor(id.zelory.compressor.Compressor) Intent(android.content.Intent) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageView(android.widget.ImageView) CropImageView(com.theartofdev.edmodo.cropper.CropImageView) View(android.view.View) IOException(java.io.IOException) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) File(java.io.File) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 38 with OnSuccessListener

use of com.google.android.gms.tasks.OnSuccessListener in project duckFood by sanjaytharagesh31.

the class OrgDataUpload method uploadFile.

private void uploadFile(Uri data, int r) {
    if (r == PICK_IMG_CODE) {
        if (image.getText().toString().length() != 0) {
            StorageReference sRef = mStorageReference.child("/Organizations/Images/" + image.getText().toString() + ".jpg");
            sRef.putFile(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                @SuppressWarnings("VisibleForTests")
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(getApplicationContext(), "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
                    imgurl = taskSnapshot.getDownloadUrl().toString();
                }
            }).addOnFailureListener(new OnFailureListener() {

                @Override
                public void onFailure(@NonNull Exception exception) {
                    Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                }
            }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {

                @SuppressWarnings("VisibleForTests")
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(getApplicationContext(), "Uploading Organization Image", Toast.LENGTH_SHORT).show();
                }
            });
        } else
            Toast.makeText(getApplicationContext(), "Please Enter Image Name", Toast.LENGTH_SHORT).show();
    } else if (r == PICK_PDF_CODE) {
        if (cert.getText().toString().length() != 0) {
            StorageReference sRef = mStorageReference.child("/Organizations/PDF Certificates/" + cert.getText().toString() + ".pdf");
            sRef.putFile(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                @SuppressWarnings("VisibleForTests")
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(getApplicationContext(), "Certificate Uploaded Successfully", Toast.LENGTH_SHORT).show();
                    certurl = taskSnapshot.getDownloadUrl().toString();
                }
            }).addOnFailureListener(new OnFailureListener() {

                @Override
                public void onFailure(@NonNull Exception exception) {
                    Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                }
            }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {

                @SuppressWarnings("VisibleForTests")
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(getApplicationContext(), "Uploading Organization Certificate", Toast.LENGTH_SHORT).show();
                }
            });
        } else
            Toast.makeText(getApplicationContext(), "Please Enter Certificate Name", Toast.LENGTH_SHORT).show();
    }
}
Also used : StorageReference(com.google.firebase.storage.StorageReference) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) OnProgressListener(com.google.firebase.storage.OnProgressListener) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 39 with OnSuccessListener

use of com.google.android.gms.tasks.OnSuccessListener in project androidApp by InspectorIncognito.

the class PositionProvider method startLocationUpdates.

private void startLocationUpdates(LocationRequest request) {
    Log.d(TAG, "startLocationUpdates");
    if (ActivityCompat.checkSelfPermission(googleApiClient.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(googleApiClient.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "Asked to update positions without permissions");
        throw new IllegalStateException("Asked to update positions without permissions");
    }
    if (googleApiClient.isConnected()) {
        requesting = true;
        if (Looper.myLooper() == null) {
            Looper.prepare();
        }
        Log.d(TAG, "Connected to API, requesting updates");
        fusedLocationProviderClient.requestLocationUpdates(request, locationCallback, null).addOnSuccessListener(new OnSuccessListener<Void>() {

            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "Task success");
            }
        }).addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception e) {
                if (e instanceof ApiException) {
                    Log.d(TAG, "onFailure: " + ((ApiException) e).getStatusMessage());
                } else {
                    Log.d(TAG, "onFailure: " + e.getMessage());
                }
            }
        });
    }
}
Also used : OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) ApiException(com.google.android.gms.common.api.ApiException) ApiException(com.google.android.gms.common.api.ApiException)

Example 40 with OnSuccessListener

use of com.google.android.gms.tasks.OnSuccessListener in project NightSkyGuide by MTBehnke.

the class MainActivity method startLocationUpdates.

private void startLocationUpdates() {
    // if settings are satisfied initialize location requests
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest).addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {

        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            locUpdates = true;
            // All location settings are satisfied.
            // noinspection MissingPermission - this comment needs to stay here to stop inspection on next line
            mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
        }
    }).addOnFailureListener(this, new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception e) {
            int statusCode = ((ApiException) e).getStatusCode();
            switch(statusCode) {
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // location settings are not satisfied, but this can be fixed by showing the user a dialog.
                    try {
                        // show the dialog by calling startResolutionForResult(), and check the result in onActivityResult().
                        ResolvableApiException resolvable = (ResolvableApiException) e;
                        resolvable.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore the error
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // location settings are not satisfied, however no way to fix the settings so don't show dialog.
                    Toast.makeText(MainActivity.this, "Location Services Unavailable", Toast.LENGTH_LONG).show();
                    useGPS = false;
                    SharedPreferences.Editor edit = preferences.edit();
                    edit.putBoolean("use_device_location", false);
                    edit.apply();
                    break;
            }
        }
    });
}
Also used : ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) LocationSettingsResponse(com.google.android.gms.location.LocationSettingsResponse) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) ApiException(com.google.android.gms.common.api.ApiException)

Aggregations

OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)44 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)43 StorageReference (com.google.firebase.storage.StorageReference)13 UploadTask (com.google.firebase.storage.UploadTask)10 File (java.io.File)9 AuthResult (com.google.firebase.auth.AuthResult)8 Uri (android.net.Uri)7 ApiException (com.google.android.gms.common.api.ApiException)6 FileDownloadTask (com.google.firebase.storage.FileDownloadTask)6 IOException (java.io.IOException)6 ResolvableApiException (com.google.android.gms.common.api.ResolvableApiException)5 LocationSettingsResponse (com.google.android.gms.location.LocationSettingsResponse)4 InputImage (com.google.mlkit.vision.common.InputImage)4 NonNull (android.support.annotation.NonNull)3 View (android.view.View)3 WritableArray (com.facebook.react.bridge.WritableArray)3 TaskFailureLogger (com.firebase.ui.auth.ui.TaskFailureLogger)3 FirebaseUser (com.google.firebase.auth.FirebaseUser)3 OnProgressListener (com.google.firebase.storage.OnProgressListener)3 StorageMetadata (com.google.firebase.storage.StorageMetadata)3