java – Changing profile picture doesn’t work correctly via gallery or camera options

I try to click profile picture to be able to change it, any option I choose both gallery and camera once click doesn’t go forward, in the sense that I don’t perform that chosen action, it just goes back in the profile. Initially it worked but going on to change various things in the app it doesn’t work anymore. How can i fix these issues?

private void showImageImportDialog() {
    // Options to display
    String options[] = {"Camera", "Gallery"};

    AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
    builder.setTitle("Pick Image").setItems(options, (dialog, which) -> {
        // Handle clicks
        if (which == 0) {
            // Camera clicked
            if (!checkCameraPermission()) {
                requestCameraPermission();
            }
            else {
                pickCamera();
            }
        }
        else {
            // Gallery clicked
            if (!checkStoragePermission()) {
                requestStoragePermission();
            }
            else {
                pickGallery();
            }
        }
    }).show();
}

private void pickGallery() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);
}

private void pickCamera() {
    ContentValues contentValues = new ContentValues();
    contentValues.put(MediaStore.Images.Media.TITLE, "GroupImage");
    contentValues.put(MediaStore.Images.Media.DESCRIPTION, "GroupImageDescription");

    imageUri = requireContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intent, IMAGE_PICK_CAMERA_CODE);
}

private void requestStoragePermission() {
    ActivityCompat.requestPermissions(requireActivity(), storagePermission, STORAGE_REQUEST_CODE);
}

private boolean checkStoragePermission() {
    return ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
}

private void requestCameraPermission() {
    ActivityCompat.requestPermissions(requireActivity(), cameraPermission, CAMERA_REQUEST_CODE);
}

private boolean checkCameraPermission() {
    boolean result =  ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
    boolean result1 = ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);

    return result && result1;
}


// Get file extension
private String getFileExtension(Uri uri) {
    ContentResolver contentResolver = requireContext().getContentResolver();
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}

private void uploadImage() throws IOException {
    // Show a progress dialog with a message
    progressDialog = new ProgressDialog(requireContext());
    progressDialog.setTitle("Please wait");
    progressDialog.setMessage("Uploading Image...");
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.show();

    // If imageUri has been initialized
    if (imageUri != null) {
        // Set storage reference
        storageReference = FirebaseStorage.getInstance().getReference("ProfileImages").child(System.currentTimeMillis()+ "." + getFileExtension(imageUri));

        // Compress the image
        Bitmap bmp = MediaStore.Images.Media.getBitmap(requireContext().getContentResolver(), imageUri);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 15, baos);
        byte[] data = baos.toByteArray();

        // Upload the image to data base
        uploadTask = storageReference.putBytes(data);

        //uploadTask = fileReference.putFile(imageUri);
        uploadTask.continueWithTask((Continuation<UploadTask.TaskSnapshot, Task<Uri>>) task -> {
            if (!task.isSuccessful()) {
                throw task.getException();
            }
            // Return the image url
            return storageReference.getDownloadUrl();
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    String mUri = downloadUri.toString();
                    // Put image url to users reference
                    reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("imageURL", mUri);
                    reference.updateChildren(map);
                    // Close the progress dialog
                }
                else {
                    Toast.makeText(requireContext(), "Failed!", Toast.LENGTH_SHORT).show();
                }
                progressDialog.dismiss();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(requireContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        });

    }
    else {
        Toast.makeText(requireContext(), "No Image Selected", Toast.LENGTH_SHORT).show();
    }
}

// Receive the result from a previous call to startActivityForResult
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // if requestCode is 1 and result code is -1 and there is some data (image selected)
    if (resultCode == Activity.RESULT_OK){
        if (requestCode == IMAGE_PICK_GALLERY_CODE && data != null && data.getData() != null) {
            // Set imageUri with the given URI data
            imageUri = data.getData();
            // If you already uploading show a toast message
            if (uploadTask != null && uploadTask.isInProgress()) {
                Toast.makeText(requireContext(), "Uploading in progress", Toast.LENGTH_SHORT).show();
            }
            // Else call uploadImage
            else {
                try {
                    uploadImage();
                    //Toast.makeText(requireContext(), "Working", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
            if (uploadTask != null && uploadTask.isInProgress()) {
                Toast.makeText(requireContext(), "Uploading in progress", Toast.LENGTH_SHORT).show();
            }
            else {
                try {
                    uploadImage();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Leave a Comment