Reputation: 139
I am displaying image from the sdcard. I searched a lot in google and got the following code
I have a button, on click of that I am calling camera feature.
public void onClick(View arg0) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
photoPath = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));
System.out.println(photoPath);
startActivityForResult(intent, TAKE_PICTURE);
}
and I have wriiten following code in onActivityResult function.
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
System.out.println("after activity"+photoPath);
Uri selectedImage = photoPath;
getContentResolver().notifyChange(selectedImage, null);
ivThumbnailPhoto = (ImageView) findViewById(R.id.ivThumbnailPhoto);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
ivThumbnailPhoto.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
Problem is I am getting photoPath value as null and it ends up with nullpointer exception. Please help me to find out issue.
Thanks in advance
Upvotes: 0
Views: 54
Reputation: 27549
You are passing a value of file path as intent extra, this is the correct behavior.
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));//here save this uri you are passing as extra.
in onActivityResult
, if RESULT_CODE
is OK
use above URI
which you passed in as EXTRA_OUTPUT
, you will get null intent/data from camera, so don't use it.
EDIT:- as you are going out of activity and coming back there can be chances of your PhotoPath variable to become NULL, you have two solution here.
1) Make photopath/uri static.
2) Use below code to save it when going out and get the value when coming into the activity.
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", photopath);
}
/*
* Here we restore the fileUri again
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the path
photoPath = savedInstanceState.getParcelable("file_uri");
}
Upvotes: 2