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?