So I am currently writing a Android App. As part of its functions, I need it to take a photo using the camera and then upload it to a firebase storage that's been set up already. This is my Android code:
package com.example.android.imagetotext;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class UploadImage extends AppCompatActivity {
private Button mUploadBtn;
private ImageView mImageView;
private Button button;
private static final int CAMERA_REQUEST_CODE = 1;
private StorageReference mStorage;
private ProgressDialog mProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
mUploadBtn = (Button) findViewById(R.id.upload);
mImageView = (ImageView) findViewById(R.id.imageView);
mStorage = FirebaseStorage.getInstance().getReference();
mProgress = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
mProgress.setMessage("Uploading image..");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Toast.makeText(UploadImage.this, "Uploading finished...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
}
}
I've taken out a lot of the Import statements for the sake of clarity but the project builds and compiles fine. The app itself loads the app, loads this page, goes to the camera and takes a picture fine. It's only when I confirm the picture that the app crashes. This is the error message:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference at com.example.android.imagetotext.UploadImage.onActivityResult(UploadImage.java:62)
which is this line of code:
StorageReference filepath = Storage.child("Photos").child(uri.getLastPathSegment());
I can't see whats wrong with it, can anyone help me out here?