Search code examples
javaandroidnullpointerexceptionbundle

Android: cannot get values using .getStringExtra


I'll just go straight to the problem. In UploadNotesActivity.java....

First, I pick a .pdf file using intent

chooseNotesBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Create intent to Open Image applications like Gallery, Google Photos
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            // Start the Intent
            startActivityForResult(intent, RESULT_LOAD_FILE);
        }
    });

and then, in `onActivityResult, I save the filePath of the picked file.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_FILE && resultCode == RESULT_OK && data != null) {
        data.putExtra("filePath", data.getData().getPath());
        choosenFile.setText(data.getStringExtra("filePath"));
    } else {
        Toast.makeText(this, "Error in choosing file",
                Toast.LENGTH_LONG).show();
    }
}

click Upload button to start upload the file

 uploadNotesBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onUploadButtonClick();
        }
    });

the onUploadButtonClick()

private void onUploadButtonClick() {
    final String serverUrlString = "http://XXXX/uploadNotes.php";
    if (getIntent().getStringExtra("filePath").isEmpty()) {
        Log.d(TAG, "filePath is null");
    } else {
        Log.d(TAG, getIntent().getStringExtra("filePath"));
    }
    final String fileToUploadPath = getIntent().getStringExtra("filePath");
    final String paramNameString = "uploaded_file";

    String fileName[] = fileToUploadPath.split("/");

    final MultipartUploadRequest request =
            new MultipartUploadRequest(this, UUID.randomUUID().toString(), serverUrlString);

    request.addFileToUpload(fileToUploadPath, paramNameString,
            fileName[fileName.length-1]+".pdf", ContentType.APPLICATION_OCTET_STREAM);

    request.setNotificationConfig(R.drawable.ic_launcher,
            getString(R.string.app_name),
            getString(R.string.uploading),
            getString(R.string.upload_success),
            getString(R.string.upload_error),
            false);

    // if you comment the following line, the system default user-agent will be used
    request.setCustomUserAgent("UploadServiceDemo/1.0");

    // set the intent to perform when the user taps on the upload notification.
    // currently tested only with intents that launches an activity
    // if you comment this line, no action will be performed when the user taps
    // on the notification
    // request.setNotificationClickIntent(new Intent(this, MainActivity.class));

    // set the maximum number of automatic upload retries on error
    request.setMaxRetries(2);

    try {
        request.startUpload();
    } catch (Exception exc) {
        Toast toast = Toast.makeText(getApplicationContext(), "Malformed upload request. " + exc.getLocalizedMessage(), Toast.LENGTH_LONG);
        toast.show();
    }
}

But the problem is, it will throw null pointer exception, which I don't quite get the reason.

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference
        at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.onUploadButtonClick(UploadNotesActivity.java:73)
        at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.access$100(UploadNotesActivity.java:19)
        at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity$2.onClick(UploadNotesActivity.java:53)

line 73: if (getIntent().getStringExtra("filePath").isEmpty())

line 19: public class UploadNotesActivity extends Activity

line 53: onUploadButtonClick();

Seems like the filePath in line 73 is empty and the way I save filePath into bundle (?) is incorrect. How to get the filePath from onActivityResult? Here's the .java class, just in case. Thank you in advance. Really need your help.


Solution

  • An Intentobject is used to pass params between activities. Ones you receives the file path you must to keep it in your activity.

    Create a filePathvariable inside your activity, set it on onActivityResult and read it on onUploadButtonClick.

    Notice that must save variable value during the onSaveInstanceState callback and restore it in onCreate because every time you turn your phone the activity is destroyed and recreated. Check this for more information: Recreating an Activity