从存储中选择图像

问题描述 投票:1回答:1

我设置了一个按钮,该按钮用于检查READ_EXTERNAL_STORAGE权限,然后打开用户手机存储的显示图像。我已经通过以下代码成功完成了此操作:

    // Choose file extended from BottomTabView, opens all images on device
    // Check for permissions before hand
    public static void openFileChooser(Context context) {
        Log.d("HomeActivity", "This is the last place a log is observed");
        if (ContextCompat.checkSelfPermission(getInstance().getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(
                    ((Activity) context),
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_CODE_STORAGE_PERMISSION
            );
        } else {
            new HomeActivity().selectImage();
        }
    }

    // Open image selector via phone storage
    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE);
        }
    }

    // Request permission results
    @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();
            }
        }
    }

    // Check if user has selected file and describe next step
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == RESULT_OK) {
            if (data != null) {

                // Get image URI
                Uri selectedImageUri = data.getData();

                if (selectedImageUri != null) {
                    try {

                        InputStream inputStream = getContentResolver().openInputStream(selectedImageUri);
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                        // Identify the selected image file, passed onto firebase
                        File selectedImageFile = new File(getPathFormUri(selectedImageUri));

                    } catch (Exception exception) {
                        Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }

    private String getPathFormUri(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;
    }

所有这些都可以在第一次尝试时完美地工作。用户看到权限对话框,按同意,然后图像选择器打开,在其手机上显示图像!但是,第二次我们尝试使用相同的按钮使应用程序崩溃。因此,基本上,在授予权限后,每次按下按钮都会使应用程序崩溃。

显示以下错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.memory.pod.debug, PID: 26684
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
        at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:98)
        at com.memory.pod.camerax.ui.home.HomeActivity.selectImage(HomeActivity.java:144)
        at com.memory.pod.camerax.ui.home.HomeActivity.openFileChooser(HomeActivity.java:137)
        at com.memory.pod.view.BottomTabView$4.onClick(BottomTabView.java:84)
        at android.view.View.performClick(View.java:7259)
        at android.view.View.performClickInternal(View.java:7236)
        at android.view.View.access$3600(View.java:801)
        at android.view.View$PerformClick.run(View.java:27892)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

我做了一个log.d来确定它失败的地方,请参考前面的代码来查看log.d。

我该如何克服这个问题?

java android android-permissions android-package-managers
1个回答
0
投票

您的else语句当前就是这样,这意味着您正在尝试创建HomeActivity的新实例并调用selectimage(),但这种方式不起作用。

else {
        new HomeActivity().selectImage();
    }

请更改为

else{
       selectImage();
    }

请尝试一下,这应该可以解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.