Search code examples
javaandroidfirebaseandroid-activityandroid-camera-intent

Take Picture and Upload to Android Firebase Error


I'm write a simple code to instant camera image capture and upload it to android firebase.
From Referance Here

Try to write full code as android studio documentation. But in logcat we can show this code occur an error uri.getLastPathSegment(). How can solve this error?

Error Logcat:
--------- beginning of crash 05-23 14:52:06.627 12364-12364/com.example.hasib_pc.firebasetest E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.hasib_pc.firebasetest, PID: 12364 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=3, result=-1, data=Intent { }} to activity {com.example.hasib_pc.firebasetest/com.example.hasib_pc.firebasetest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference at android.app.ActivityThread.deliverResults(ActivityThread.java:4268) at android.app.ActivityThread.handleSendResult(ActivityThread.java:4312) at android.app.ActivityThread.-wrap19(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1644) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference

MainActivity Full code:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    public static final int IMAGE_CAPTURE_CODE = 3;
    private Button uploadBtn;
    private ImageView showImage;
    private StorageReference mStorage;
    private ProgressDialog progressDialog;

    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
        Log.d(TAG, "createImageFile: start.");
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );

        mCurrentPhotoPath = image.getAbsolutePath();
        Log.d(TAG, "createImageFile: End.");
        return image;
    }

    private void takePictureIntent() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                Log.e(TAG, "takePictureIntent: IOException: "+ex.getMessage(),ex);
            }
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider",
                        photoFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(intent, IMAGE_CAPTURE_CODE);
                Log.d(TAG, "takePictureIntent: End.");
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        uploadBtn = findViewById(R.id.uploadBtnId);
        showImage = findViewById(R.id.imageShowId);

        progressDialog = new ProgressDialog(this);

        uploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePictureIntent();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: Started.");
        if(requestCode == IMAGE_CAPTURE_CODE && resultCode == RESULT_OK){
            Log.d(TAG, "onActivityResult: start uploading");
            progressDialog.setMessage("Uploading...");
            progressDialog.show();
            Uri uri = data.getData();

            Log.d(TAG, "onActivityResult: set filepath");
            StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
            Log.d(TAG, "onActivityResult: try to putFile");
            filepath.putFile(uri).addOnSuccessListener(new    OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Log.d(TAG, "onSuccess: started.");
                    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();
                }
            });
        }
    }
}

Solution

  • It was my mistake. I found the solution. Create a Uri instantce veriable. private Uri photoURI;

    Then send this Uri with Intent putExtra method.

    photoURI = FileProvider.getUriForFile(this,
                            "com.example.android.fileprovider",
                            photoFile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
    

    and pass the uri object via StorageReference putFile method
    filepath.putFile(photoURI)

    I called Uri photoURI in onCreate method insted of Class instance veriable that's why got NullPointerException.