This question already has answers here:
Getting Uri Null in capture photo from camera intent in samsung mobile

(3个答案)


5年前关闭。




我正在2种不同的物理设备中调试我的应用程序:
  • 摩托罗拉Moto G,Android 4.4.2
  • LG OPTIMUS L5 II,Android 4.1.2

  • 我按一个按钮调用相机:
    buttonCamera.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
                }
            });
    

    我管理这样的 Intent 结果:
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                Uri selectedImage = data.getData(); // <-- Sometimes null
        }
    

    这里的问题是,在Motorola Moto G中data.getData()为null,但在LG OPTIMUS中不是ojit_code,这是为什么?如何避免在Motorola Moto G中获得零值?

    最佳答案

    这个答案有点晚了,但是我刚才也遇到了同样的问题,我找到了一个解决方案:

    private static final String STATE_FILE_URI = "state_file_uri";
    private static final int BROWSE_CAMERA = 111;
    private String fileUri;
    
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            outState.putString(STATE_FILE_URI, fileUri);
            super.onSaveInstanceState(outState);
        }
    
        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            fileUri = savedInstanceState.getString(STATE_FILE_URI);
            super.onRestoreInstanceState(savedInstanceState);
        }
    
        private void takePictureIntent(){
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            fileUri = "your_uri";
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(fileUri)));
            startActivityForResult(takePictureIntent, BROWSE_CAMERA);
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == RESULT_OK) {
                if (requestCode == BROWSE_CAMERA) {
                    if (data == null) {
                        onDeliveryPicture(Uri.parse("file://" + fileUri));
                    } else {
                        onDeliveryPicture(data.getData());
                    }
                }
            }
        }
    
        private void onDeliveryPicture(Uri uri) {
            ...
        }
    

    希望能帮助到你!

    10-06 13:41