mendoh
mendoh

Reputation: 1

ActivityResultLauncher for uploading profile picture

I want to pick a picture from the phone gallery to upload as the profile picture of the user in an app. And I want to get the URI for it so I can store it in the user database.

activityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() == RESULT_OK && result.getData()!= null) {
                    Bundle data = result.getData().getExtras();
                    Uri myUri = (Uri) data.get("data");
                    profilePic.setImageURI(myUri);
                }
        });

    uploadPicture.setOnClickListener(view -> {
        Intent imagePickerIntent = new Intent(Intent.ACTION_PICK, 
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        imagePickerIntent.setType("image/*");
        activityResultLauncher.launch(imagePickerIntent);
    });

Right now I can enter code here and open the gallery and browse through pictures but the app crashes when i select one and try to go back to my app from the gallery. Can anyone tell me how to fix my code? Thanks

Upvotes: 0

Views: 4199

Answers (1)

Rudra Rokaya
Rudra Rokaya

Reputation: 685

method to start Activity.

 private void selectImage(){
    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    activityResultLauncher.launch(intent);
}

Then, override onRequestPermissionsResult() as follows:

 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_CODE_STORAGE_PERMISSION && grantResults.length > 0){
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
            selectImage();
        }else {
            Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
        }
    }
}

Another, method as follows:

 private void displayResult(){
    activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK){
                    Intent data = result.getData();
                    if (data != null){
                        Uri selectedImageUri = data.getData();
                        if (selectedImageUri != null){
                            try {
                                InputStream inputStream = getContentResolver().openInputStream(selectedImageUri);
                                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                noteBinding.imageNote.setImageBitmap(bitmap);
                                selectedImagePath = getPathFormatUri(selectedImageUri);
                            }catch (Exception e){
                                Toast.makeText(CreateNoteActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
            });
}

Another method for returning url/path for the image.

 private String getPathFormatUri(Uri contentUri){
    String filePath;
    Cursor cursor = getContentResolver()
            .query(contentUri,null,null,null,null);
    if (cursor == null){
        filePath = contentUri.getPath();
    }else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex("_data");
        filePath = cursor.getString(index);
        cursor.close();
    }

    return filePath;
}

Upvotes: 0

Related Questions