在显示文件选择器中按下

时间:2019-03-20 15:17:24

标签: android android-activity

private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

}

嘿。我使用该代码从存储中选择图像。但是如果我按一下小工具中的“后退”按钮。他是fc。

如何在取消选择的仓库中提供条件,而不是强制关闭?
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST) {
        filePath = data.getData();
        if(filePath != null) {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);
                Toast.makeText(this, data.getDataString(), Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(filePath == null){
            startActivity(new Intent(this,HalamanUser.class));
        }
    } else if (requestCode == CAMERA_REQUEST) {

        Log.i("hello", "REQUEST cALL");
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);

        } catch (Exception e) {
            Log.i("hello", "Exception" + e.getMessage());
        }

    }else {
        startActivity(new Intent(this,HalamanUser.class));
    }
}

1 个答案:

答案 0 :(得分:0)

当用户按下时,结果为RESULT_CANCELED,收到的data为空。因此,当您调用data.getData()时,就像在空对象上调用getData()一样,应用程序崩溃。解决此问题的方法有几种:您可以检查resultCode是什么,并确保它是RESULT_OK。您还可以简单地检查data的Intent是否为null,然后再尝试从中获取数据:

if (requestCode == PICK_IMAGE_REQUEST) {
    if (data != null) {
        filePath = data.getData(); 
    } else {
        // Note: if filePath is by default null, you don't need this else statement
        filePath = null; 
    }
    if (filePath != null) {
        ...