1

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 + "%");
                            }
                        });
    }
}

}

  • If you understand Kotlin, I think that this [resource](https://medium.com/firebase-tips-tricks/how-to-upload-an-image-to-cloud-storage-and-save-the-url-in-firestore-42711ca1df46) will help. – Alex Mamo Aug 10 '22 at 09:49

1 Answers1

0

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Please have a look at this project , I'm using this project , please help me mate : https://github.com/Everyday-Programmer/Images-from-Specific-Folder –  Aug 10 '22 at 07:33
  • Did you read the README.md? - It says: *"Change this path to the folder path which you want to access."* `String filePath = "/storage/emulated/0/Pictures";`. Seriously dude, try reading the instructions ... rather than relying on someone else to do it for you. – Stephen C Aug 10 '22 at 07:56
  • But I want path of selected image in ImageViewerActivity not the folder where images are stored, that's the problem , correct me if I'm wrong mate. Should I rename the filepath to something else like is there any conflict within those? –  Aug 10 '22 at 08:15
  • OK. So compare the code in the example to your code. The example code doesn't do `filepath = Uri.parse(path);`. Why are you doing that? Why are you doing it **there**? Before you have gotten the actual path from the intent? If you are going to modify the code, you need to **understand** it first. – Stephen C Aug 10 '22 at 08:38
  • I attached a upload button in this class , but to upload image to firebase I need the Uri path of selected image in imageview and I'm not able to figure out what is the path of selected image, please help if you can I'm breaking my head from past 2 days –  Aug 10 '22 at 08:55
  • Yes. But read your code. I mean **read** it. You can't turn the path into a `Uri` before you have gotten the path. – Stephen C Aug 10 '22 at 09:01
  • Can you figure it out for me please? I tried everything I knew. –  Aug 10 '22 at 09:08
  • No mate. You need to read and understand the code that you wrote for yourself. I have already told you what you should be looking for. Sure ... I could fix your code for you. But then you wouldn't learn to do it yourself. Maybe this will help: read https://rubberduckdebugging.com and then apply the rubberduck technique to the first 12 lines of the `onCreate` method. Seriously. – Stephen C Aug 10 '22 at 09:25
  • If you really want someone to do your programming for you, I suggest you visit a freelance programmer site; aka a "rent a coder" site. This is the last help I will be offering you. – Stephen C Aug 10 '22 at 09:27
  • Thank you for giving your time have a great day –  Aug 10 '22 at 09:43