Uploading image (ACTION_IMAGE_CAPTURE) to Firebase storage [duplicate]

夙愿已清 提交于 2020-02-07 08:39:33

问题


EDIT: The discussion on this issue has been carried to another question: Image capture with camera & upload to Firebase (Uri in onActivityResult() is null) PLEASE check it out! I did some manipulations (following the android documentation) but still getting same problem.

So here I'm trying to do a simple task of capturing an image with camera and uploading it to my storage database on Firebase. I have the following button to do the job:

b_capture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, CAMERA_REQUEST_CODE);
        }
    });

and the following code for the upload:

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

    if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
        progressDialog.setMessage("Uploading...");
        progressDialog.show();
        Uri uri = data.getData();
        StorageReference filepath = storage.child("Photos").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
            }
        });
      }
    }

in the app I'm able to take picture, but after I confirm the picture taken the APP CRASHES and I get the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference

So, I understand that the "Uri" does not have anything in it, but I'm confused about what can be done. Need help.

And yes, I've checked all permissions, Firebase connections, Gradle sync etc.


回答1:


You need to re-read the documentation and follow the example to create a file and store its Uri in the image capture intent. This is the code from the documentation you need to add:

String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ...
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                                                  "com.example.android.fileprovider",
                                                  photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}


b_capture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dispatchTakePictureIntent()

            //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //startActivityForResult(intent, CAMERA_REQUEST_CODE);
        }
    });



回答2:


Question solved in the following discussion: Image capture with camera & upload to Firebase (Uri in onActivityResult() is null) Thanks to everyone who participated!



来源:https://stackoverflow.com/questions/40709765/uploading-image-action-image-capture-to-firebase-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!