Why I'm getting java.lang.NullpointerExcetion: uriString in my Activity?

Viewed 42

Hey there im getting an error "java.lang.NullpointerExcetion: uriString" at filepath = Uri.parse(path); located inside onCreate. im trying to upload images to firebase and for that i need filepath, what im doing wrong?, I have used filepath in uploadImage() as path for image, the selected image from array is displayed in this Activity and i want to upload the selected image to firebase, please see the code:

private Uri filepath;
FirebaseStorage storage;
StorageReference storageReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_viewer);
    String path = null;
    filepath = Uri.parse(path);
    ImageView imageView = findViewById(R.id.imageView);
    storage = FirebaseStorage.getInstance();
    storageReference = storage.getReference();
    Intent intent = getIntent();
    if (intent != null) {
        Glide.with(ImageViewerActivity.this).load(intent.getStringExtra("image")).placeholder(R.drawable.ic_baseline_broken_image_24).into(imageView);
        path = intent.getStringExtra("image");
    }
    ImageButton uploadClicks = findViewById(R.id.UploadClicks);
    uploadClicks.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            uploadImage();
        }
    });

    ImageButton share = findViewById(R.id.shareImage);
    String finalPath = path;
    share.setOnClickListener(v -> new ShareCompat.IntentBuilder(ImageViewerActivity.this).setStream(Uri.parse(finalPath)).setType("image/*").setChooserTitle("Share Image").startChooser());

    ImageButton delete = findViewById(R.id.deleteImage);
    delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MaterialAlertDialogBuilder alertDialogBuilder = new MaterialAlertDialogBuilder(ImageViewerActivity.this);
            alertDialogBuilder.setMessage("Are you sure you want to delete this image ?");
            alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String[] projection = new String[]{MediaStore.Images.Media._ID};
                    String selection = MediaStore.Images.Media.DATA + " = ?";
                    String[] selectionArgs = new String[]{new File(finalPath).getAbsolutePath()};
                    Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    ContentResolver contentResolver = getContentResolver();
                    Cursor cursor = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
                    if (cursor.moveToFirst()) {
                        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                        Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                        try {
                            contentResolver.delete(deleteUri, null, null);
                            boolean delete1 = new File(finalPath).delete();
                            Log.e("TAG", delete1 + "");
                            Toast.makeText(ImageViewerActivity.this, "Deleted Successfully", Toast.LENGTH_SHORT).show();
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(ImageViewerActivity.this, "Error Deleting Video", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(ImageViewerActivity.this, "File Not Find", Toast.LENGTH_SHORT).show();
                    }
                    cursor.close();
                }
            });
            alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialogBuilder.show();
        }
    });
}

private void uploadImage()
{
    if (filepath != null) {

        // Code for showing progressDialog while uploading
        ProgressDialog progressDialog
                = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        // Defining the child of storageReference
        StorageReference ref
                = storageReference
                .child(
                        "images/"
                                + UUID.randomUUID().toString());

        // adding listeners on upload
        // or failure of image
        ref.putFile(filepath)
                .addOnSuccessListener(
                        new OnSuccessListener<UploadTask.TaskSnapshot>() {

                            @Override
                            public void onSuccess(
                                    UploadTask.TaskSnapshot taskSnapshot)
                            {

                                // Image uploaded successfully
                                // Dismiss dialog
                                progressDialog.dismiss();
                                Toast
                                        .makeText(ImageViewerActivity.this,
                                                "Image Uploaded!!",
                                                Toast.LENGTH_SHORT)
                                        .show();
                            }
                        })

                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e)
                    {

                        // Error, Image not uploaded
                        progressDialog.dismiss();
                        Toast
                                .makeText(ImageViewerActivity.this,
                                        "Failed " + e.getMessage(),
                                        Toast.LENGTH_SHORT)
                                .show();
                    }
                })
                .addOnProgressListener(
                        new OnProgressListener<UploadTask.TaskSnapshot>() {

                            // Progress Listener for loading
                            // percentage on the dialog box
                            @Override
                            public void onProgress(
                                    UploadTask.TaskSnapshot taskSnapshot)
                            {
                                double progress
                                        = (100.0
                                        * taskSnapshot.getBytesTransferred()
                                        / taskSnapshot.getTotalByteCount());
                                progressDialog.setMessage(
                                        "Uploaded "
                                                + (int)progress + "%");
                            }
                        });
    }
}

}

1 Answers

Your code says:

String path = null;
filepath = Uri.parse(path);

and you ask why Uri.parse(path) throws a NullPointerException.

Answer: Because path is null.

Why?

Answer: Because you assigned null to it in the previous line!

How to fix it?

Answer: Don't do that. Instead, get a non-null value for the path from somewhere.

Unfortunately, there aren't enough clues in your code to figure out where it would get the value from, so I'm afraid you will have to figure that out for yourself.

Related