2

So I've got a problem, previously mentioned in the question I've asked: Uploading image (ACTION_IMAGE_CAPTURE) to Firebase storage

I've searched for the issue a bit more, and applied the Android Studio documentation: https://developer.android.com/training/camera/photobasics.html#TaskPhotoView

So, before you read the code, I basically want to say what is needed: I just want to capture a photo with camera and upload it directly to Firebase storage. To do that I need the Uri to contain the picture I just took (Uri.getLastPathSegment()), however I still couldn't succeed doing this.

So now, this is what my code look like (only related parts): AndroidManifest.xml:

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
</provider>

I have the res/xml/file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images"   path="Android/data/com.serjardovic.firebasesandbox/files/Pictures" />
</paths>

and finaly the MainActivity.java:

public class MainActivity extends AppCompatActivity {

private Button b_gallery, b_capture;
private ImageView iv_image;
private StorageReference storage;
private static final int GALLERY_INTENT = 2;
private static final int CAMERA_REQUEST_CODE = 1;
private ProgressDialog progressDialog;

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, CAMERA_REQUEST_CODE);
        }
    }
}


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

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

    b_gallery = (Button) findViewById(R.id.b_gallery);
    b_capture = (Button) findViewById(R.id.b_capture);
    iv_image = (ImageView) findViewById(R.id.iv_image);

    progressDialog = new ProgressDialog(this);

    b_capture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            dispatchTakePictureIntent();

        }
    });
}

@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();
            }
        });
        }
    }
}

Need a solution! Still, the app crashes after I take the picture and press the confirm button and I get the following crash report:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.serjardovic.firebasesandbox/com.serjardovic.firebasesandbox.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference

Community
  • 1
  • 1
Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52

2 Answers2

1

Try changing mCurrentPhotoPath = image.getAbsolutePath(); to mCurrentPhotoPath = "file:" + image.getAbsolutePath();. I didnt spot any other differences from my code, which has worked.

wilkas
  • 1,161
  • 1
  • 12
  • 34
  • 1
    No, unfortunately this small tweak didn't work as well. Maybe it's something else? If you could check again, or maybe you want to see some other files? – Sergey Emeliyanov Nov 21 '16 at 07:13
  • Have you dealt with camera permissions? Most possibly a runtime permission request is needed, I've only tested it by enabling camera permission in virtual device settings. – wilkas Nov 21 '16 at 07:17
  • INTERNET, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, CAMERA. I have these permissions, and it successfully opens the camera and I can take a picture. The problem seems to be the Uri which does not take the image so that I can upload it to Firebase. – Sergey Emeliyanov Nov 21 '16 at 07:20
  • 1
    My main XML - https://codeshare.io/5RArW2 My MainActivity Java - https://codeshare.io/aYBrnG I have just test it and my sample still works for me. Please check the code and see if you have missed anything. It has two buttons, one to pickup from gallery, other to take a picture with camera. Then uploads its to Firebase and shows it in ImageView. Of course you need to setup your application with Firebase. If you find what was wrong with your code, please share. – wilkas Nov 21 '16 at 07:23
  • Thanks a LOT! I've found the mistake, so dumb :( I forgot to add the photoURI into filepath.putFile(photoURI), it was just filepath.putFile(uri) - no wonder it did crash just as before. – Sergey Emeliyanov Nov 21 '16 at 07:41
0

So the answer is simple, thanks to @wilkas help in the comments. I just forgot to add the photoURI into filepath.putFile(photoURI), it was just filepath.putFile(uri), so the addition of code simply did nothing until I notices this. Hope this Q&A will help someone else with a similar problem!

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52