简体   繁体   English

ActivityResultLauncher 用于上传头像

[英]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.我想获取它的 URI,以便将其存储在用户数据库中。

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.现在我可以在这里输入代码并打开图库并浏览图片,但是当我使用 select 并尝试从图库中将 go 返回到我的应用程序时,应用程序崩溃了。 Can anyone tell me how to fix my code?谁能告诉我如何修复我的代码? Thanks谢谢

method to start Activity.启动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:然后,按如下方式覆盖 onRequestPermissionsResult():

 @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.返回图像的 url/路径的另一种方法。

 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM