0

I'm trying to upload a pdf file to the server in my android app with java.
Using the emulator, the app keeps crashing when I try to upload the file

The error I get:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.lastIndexOf(java.lang.String)' on a null object reference at com.example.parttimejob.ApplicantRegisterActivity.onActivityResult(ApplicantRegisterActivity.java:202)

Here's what happens:

After the android user presses a button to choose a pdf,a setOnClickListener activates, here is the code:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("application/pdf");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select PDF : "), 1);
            }
        });

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Uri selectedFileUri = data.getData();   // get the file uri
            filePath = getPath(selectedFileUri);    // get the path of the uri
            file_name = filePath.substring(filePath.lastIndexOf("/") + 1);  // get the name of the file

            aController.setFilename(file_name);
            aController.setFilepath(filePath);

        }
    }


    public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

I suspect the file path to be the problem, filePath = getPath(selectedFileUri);

What's wrong with the code though?

Mohammad
  • 21
  • 4
  • Which error do you exactly get? – Funny Moments May 20 '22 at 07:51
  • Oh silly me I forgot that Here's the error: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.lastIndexOf(java.lang.String)' on a null object reference at com.example.parttimejob.ApplicantRegisterActivity.onActivityResult(ApplicantRegisterActivity.java:202) – Mohammad May 20 '22 at 07:58
  • `NullPointerException`. Dont use a pointer variable that is null. – blackapps May 20 '22 at 08:15
  • The title of your post is wrong as your problem has nothing to do with uploading – blackapps May 20 '22 at 08:19
  • There is no requirement for `MediaStore` to know anything about that `Uri`, and there is no requirement for `DATA` to contain anything. And there is no requirement for `ACTION_GET_CONTENT` to give you a `Uri` that references a file on the local filesystem that you can access. – CommonsWare May 20 '22 at 10:54

0 Answers0