OnActivityResult:在捕获照片期间,Uri和getData是一个空对象

时间:2016-10-20 08:53:19

标签: java android firebase android-camera firebase-storage

我的Uri对象有问题。用户应该拍照,然后将其发送到Firebase存储。但是onActivityResult是错误的。

我阅读了很多主题(https://developer.android.com/training/camera/photobasics.html,StackOverFlow也是如此),但这段代码无效。

有一个错误:

尝试在空对象引用上调用虚方法'java.lang.String android.net.Uri.getLastPathSegment()'

以下是代码:

 mUploadBtn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {

      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      if (intent.resolveActivity(getPackageManager()) != null) {  

           startActivityForResult(intent, CAMERA_REQUEST_CODE);
               }
             }
         });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


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

            mProgress.setMessage("Uploading Image...");
            mProgress.show();

            Uri uri = data.getData();

            StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());


            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    mProgress.dismiss();

                    Uri downloadUri = taskSnapshot.getDownloadUrl();

                    Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);

                    Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
                }
            });

        }
    }
}

正如我所检查的那样,onActivityResult中的数据(Intent)等于NULL,因此uri也是null。

那么,我该如何解决这个挑战并使其可用?我应该使用位图来访问照片吗?

有人可以帮我解决这个问题吗?

此致

4 个答案:

答案 0 :(得分:1)

我想出了我的问题。 它现在有效。

    private ProgressDialog mProgress;
    private Button mUploadBtn;
    private ImageView mImageView;
    Uri picUri;
    private StorageReference mStorage;

    private static final int CAMERA_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mStorage = FirebaseStorage.getInstance().getReference();

        mUploadBtn = (Button) findViewById(R.id.uploadBtn);
        mImageView = (ImageView) findViewById(R.id.imageView);

        mProgress = new ProgressDialog(this);

        mUploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                File file=getOutputMediaFile(1);
                picUri = Uri.fromFile(file); // create
                i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file

                startActivityForResult(i, CAMERA_REQUEST_CODE);
            }
        });
    }

    /** Create a File for saving an image */
    private  File getOutputMediaFile(int type){
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyApplication");

        /**Create the storage directory if it does not exist*/
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                return null;
            }
        }

        /**Create a media file name*/
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == 1){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_"+ timeStamp + ".png");
        } else {
            return null;
        }

        return mediaFile;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ) {

            mProgress.setMessage("Uploading Image...");
            mProgress.show();


            Uri uri = picUri;

            StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());


            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    mProgress.dismiss();

                    Uri downloadUri = taskSnapshot.getDownloadUrl();

                    Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);

                    Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
                }
            });
        }
    }

答案 1 :(得分:0)

之前我遇到了同样的问题所以我确保在下面调用onActivityResult时检查我可以检查的所有内容是我的代码。

首先我使用此意图来捕捉图像

    File photoFile;
    URI uri;

    mUploadBtn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {

          Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (takePhotoIntent.resolveActivity(getPackageManager()) != null)
                        {
                            try
                            {
                                photoFile = Create_ImageFile();
                            }
                            catch (Exception e)
                            {
                                Log.e("file", e.toString());
                            }
                            if (photoFile != null)
                            {
                                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile()));
                            }
                        }


        startActivityForResult(takePhotoIntent, CAMERA_REQUEST_CODE);
                 }
             });
        }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
    {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch (requestCode) {

            case CAMERA_REQUEST_CODE:

                if (resultCode == Activity.RESULT_OK)
                {
                    try
                    {
                        Uri selectedImageURI = null;
                        ByteArrayOutputStream bos;
                        Bitmap bitmap = null;
                        int orientation;
                        ExifInterface exif = null;
                        FileOutputStream fos = null;

                        bos = new ByteArrayOutputStream();
                        try
                        {
    uri=imageReturnedIntent.getData();
                            selectedImageURI = imageReturnedIntent.getData();
                            bitmap= BitmapFactory.decodeFile(GetRealPathFromURI(selectedImageURI));
                            exif = new ExifInterface(GetRealPathFromURI(selectedImageURI));
                            fos = new FileOutputStream(GetRealPathFromURI(selectedImageURI));
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }


                        if(bitmap==null)
                        {
uri=Uri.fromFile(photoFile.getAbsoluteFile()));
                            bitmap=BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                            exif = new ExifInterface(photoFile.getAbsolutePath());
                            fos = new FileOutputStream(photoFile.getAbsolutePath());
                        }

                        if(bitmap==null)
                        {
                            String imagePath = getPathGalleryImage(imageReturnedIntent);
                            bitmap = BitmapFactory.decodeFile(imagePath);
                            exif = new ExifInterface(imagePath);
                            fos = new FileOutputStream(imagePath);
                        }


                        Log.e("PhotoFile",photoFile.getAbsolutePath());


                        // Bitmap bitmap =(Bitmap) imageReturnedIntent.getExtras().get("data");
                        //bitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(), false);


                        orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

                        Log.e("ExifInteface .........", "rotation ="+orientation);

                        //exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);

                        Log.e("orientation", "" + orientation);
                        Matrix m = new Matrix();

                        if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
                            m.postRotate(180);
                            //m.postScale((float) bm.getWidth(), (float) bm.getHeight());
                            // if(m.preRotate(90)){
                            Log.e("in orientation", "" + orientation);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);

                        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                            m.postRotate(90);
                            Log.e("in orientation", "" + orientation);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);

                        }
                        else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
                        {
                            m.postRotate(270);
                            Log.e("in orientation", "" + orientation);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
                        }
                        else
                        {
                            m.postRotate(0);
                            Log.e("in orientation", "" + orientation);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
                        }

                        //CropImage.activity(selectedImageURI).setGuidelines(CropImageView.Guidelines.ON).start(this);

                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                        userProfileIMG.setImageBitmap(bitmap);

StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());


                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                break;
        }

    }


    private String getPathGalleryImage(Intent imageURI)
    {
        Uri selectedImage = imageURI.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String imagePath = cursor.getString(columnIndex);
        cursor.close();

        return imagePath;
    }


    /**
     * When image is returned we get its real path
     **/
    private String GetRealPathFromURI(Uri contentURI)
    {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }


    private File Create_ImageFile() throws IOException
    {

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp;
        File mediaStorageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = new File(mediaStorageDir.getAbsolutePath() + File.separator + imageFileName);
        return image;
    }

在这个过程之后我总是有一个位图来使用它,因为我想要。

答案 2 :(得分:0)

使用

获取捕获图像的实际图像预定义路径
Intent cameraIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
this.startActivityForResult(cameraIntent, 101); 

捕获图像后,您可以在cameraIntent中设置的路径上获取捕获的图像。如果您不想设置预定义路径,请检查Intent数据。

if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) {
                try {

                    path_mm = "Onsuccess_resultcode";
                    generateNoteOnSD("photo34.txt", path_mm);
                    Bitmap photo = null;
                    if (data == null) {
                    //get Bitmap  here.
                    } 
               else {
                    Uri u1 = data.getData();
                    //get uri and find actual path on that uri.
                     }
                     }catch(Exception ex)
                     {}}

答案 3 :(得分:0)

始终使用以下路径创建文件并存储捕获的图像

File photoFile = null;     

mUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  if (intent.resolveActivity(getPackageManager()) != null) {  

        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
           }
         }
     });
}

private File createImageFile() throws IOException {
    // Create an image mSelectedFile name
    String timeStamp = new SimpleDateFormat(Constants.PHOTO_DATE_FORMAT, Locale.ENGLISH).format(new Date());
    String imageFileName = "IMG_" + timeStamp;
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File file = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );


    return file;
}

然后使用此文件&#34; photoFile&#34;并在onActivityResult中根据需要使用它。