I have looked through here for help but nothing seems to be completely related or helped me fix the error I am facing. I copied everything from https://developer.android.com/training/camera/photobasics.html#TaskScalePhoto
How do I remove the null pointer from this line?
Bundle extras = data.getExtras();
The rest of the code is here.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
//galleryAddPic();
}
//Creates Intent
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.joseph.webber.dartapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
//Creates File Path and Name
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Stacktrace
>06-04 01:28:39.945 20181-20181/com.joseph.webber.dartapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.joseph.webber.dartapp, PID: 20181
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.joseph.webber.dartapp/com.joseph.webber.dartapp.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4925)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4968)
at android.app.ActivityThread.access$1600(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1849)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.joseph.webber.dartapp.LoginActivity.onActivityResult(LoginActivity.java:98)
at android.app.Activity.dispatchActivityResult(Activity.java:7137)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4921)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4968)
at android.app.ActivityThread.access$1600(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1849)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Related
I have a camera intent that takes a photo then returns back to the activity. It works fine on the emulator but on a real device, it crashes after taking the photo and accepting it.
The error I get on the device is this
Process: com.example.smartcalendar, PID: 29675
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=101, result=-1, data=null} to activity {com.example.smartcalendar/com.example.smartcalendar.DailyActivity}: java.lang.NullPointerException: null reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4605)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4647)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7045)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Caused by: java.lang.NullPointerException: null reference
at com.google.android.gms.common.internal.Preconditions.checkNotNull(com.google.android.gms:play-services-basement##17.1.1:2)
at com.google.mlkit.vision.common.InputImage.<init>(com.google.mlkit:vision-common##16.1.0:74)
at com.google.mlkit.vision.common.InputImage.fromBitmap(com.google.mlkit:vision-common##16.1.0:12)
at com.example.smartcalendar.DailyActivity.onActivityResult(DailyActivity.java:236)
at android.app.Activity.dispatchActivityResult(Activity.java:7759)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4598)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4647)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7045)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
These are the relevant code blocks
Intent camintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (camintent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile;
photoFile = null;
try {
photoFile = **createImageFile();**
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Error occured creating the file");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
camintent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
**startActivityForResult(camintent, 101);**
}
}
That launches the activityonresult but before that, it calls this method to createImageFile.
String currentPhotoPath;
private File **createImageFile()** throws IOException {
// String currentPhotoPath;
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = **getExternalFilesDir(Environment.DIRECTORY_PICTURES)**;
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = **image.getAbsolutePath()**;
return image;
}
Inside the onActivityResult, this is the code I have for now.
// Bitmap takenImage = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
Bitmap bm=null;
if (data != null) {
bm = BitmapFactory.decodeFile(currentPhotoPath);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Log.e(TAG, "onActivityResult: "+ BitmapCompat.getAllocationByteCount(bm));
bm.compress(JPEG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
Log.e(TAG, "onActivityResult: "+ BitmapCompat.getAllocationByteCount(decoded));
}
Here is the provider in the Android Manifest
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
Here is file_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
</paths>
For the file_paths.xml I tried to follow this answers' advice.
My suspicions are that the problem lies somewhere in trying to save the photo to storage and retrieve it later as well.
I am new to Android development and are a bit stuck trying to save a image to the gallery. I have followed the guidelines on https://developer.android.com/training/camera/photobasics, and it works fine until I try to save the image to the gallery on the phone using getExternalStoragePublicDirectory.
When I use the getExternalFilesDir() all works, but when i try to use getExternalStoragePublicDirectory to get the picture to the gallery Ii got a NullPointerException.
I have added the WRITE_EXTERNAL_STORAGE permission to the manifest.
I have tried to read other posts about this, but havent found any soulutions to this problem.
Heres my code. If annyone culd help me finding out whats cousing the NullPointerException I would be thankful.
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
And heres my error in Logcat:
08-02 20:04:12.920 17455-17455/com.example.android.fishlist E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.fishlist, PID: 17455
java.lang.NullPointerException
at java.io.File.<init>(File.java:282)
at com.example.android.fishlist.NewCatch.galleryAddPic(NewCatch.java:192)
at com.example.android.fishlist.NewCatch.access$200(NewCatch.java:45)
at com.example.android.fishlist.NewCatch$2.onClick(NewCatch.java:101)
at android.view.View.performClick(View.java:6891)
at android.widget.TextView.performClick(TextView.java:12651)
at android.view.View$PerformClick.run(View.java:26083)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Hi so i want to take a picture with camera intent but after taking the picture i get the following error:
ERROR:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {radautiul_civic.e_radauti/radautiul_civic.e_radauti.Civic_Alert}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5004)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5047)
at android.app.ActivityThread.access$1600(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1875)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at radautiul_civic.e_radauti.Civic_Alert.onActivityResult(Civic_Alert.java:86)
at android.app.Activity.dispatchActivityResult(Activity.java:7165)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5000)
Here is my code:
static final int REQUEST_TAKE_PHOTO = 1;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
And here is my StartActivityForResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
imgBitmap = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(imgBitmap);
Toast.makeText(getApplicationContext(),mCurrentPhotoPath,Toast.LENGTH_SHORT);
}
}
So this is what I did before error: 1.Opened my camera intent 2.Took the picture 3.I pressed OK and i got that the data from result is empty error
I followed this documentation from google: https://developer.android.com/training/camera/photobasics.html#TaskGallery
So can you guys tell me what i did wrong? Thanks in advance
If you pass the extra parameter MediaStore.EXTRA_OUTPUT with the camera intent then camera activity will write the captured image to that path and it will not return the bitmap in the onActivityResult method.
If you will check the path which you are passing then you will know that actual camera had written the captured file in that path.
So you need some changes in your code
To start the camera activity use
Intent cameraIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
After capturing the image you will get captured image in the bitmap format in onActivityResult method. Now when you get the bitmap use it as you want to.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Bitmap bmp = intent.getExtras().get("data");
//Use the bitmap as you want to
}
}
Note: Here bitmap object consists of thumb image, it will not have a full resolution image
Some useful references
http://dharmendra4android.blogspot.in/2012/04/save-captured-image-to-applications.html
How to get camera result as a uri in data folder?
Model: Samsung SM-G900F (Android 5.0)
Code to launch camera:
File file = new File(getExternalFilesDir(null),"video.mp4");
Uri uri = FileProvider.getUriForFile(this, "example.com.myapplication.fileprovider", file);
final Intent takePictureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION| Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
final List<ResolveInfo> resInfoList =
getPackageManager()
.queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (final ResolveInfo resolveInfo : resInfoList) {
final String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
startActivityForResult(takePictureIntent, 42);
Log:
11-03 11:40:00.073 30377-30377/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sec.android.app.camera, PID: 30377
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2002, result=-1, data=Intent { act=inline-data dat=content://example.com.myapplication.fileprovider/external/Android/data/example.com.myapplication/files/video.mp4 (has extras) }} to activity {com.sec.android.app.camera/com.sec.android.app.camera.Camcorder}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.deliverResults(ActivityThread.java:3974)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4017)
at android.app.ActivityThread.access$1400(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1471)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetLong(Native Method)
at android.database.CursorWindow.getLong(CursorWindow.java:524)
at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:75)
at android.database.CursorWrapper.getLong(CursorWrapper.java:106)
at com.sec.android.app.camera.Camera.onActivityResult(Camera.java:6956)
at android.app.Activity.dispatchActivityResult(Activity.java:6475)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3970)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4017)
at android.app.ActivityThread.access$1400(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1471)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Looks like video capturing works only with file uri and doesn't work with content uri.
Do you have the same issues? Could you suggest some general solution?
This helped me:
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", f);
} else {
uri = Uri.fromFile(f);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
This is working for me.
private void launchCamera() {
Intent captureVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (captureVideoIntent.resolveActivity(getPackageManager()) != null)
{
Uri videoUri = null;
try {
videoUri = getOutputMediaFileUri();
} catch (Exception ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (videoUri != null) {
captureVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
startActivityForResult(captureVideoIntent, REQUEST_CAMERA);
}
}
}
/**
* Creating file uri to store image/video
*/
private Uri getOutputMediaFileUri() {
if(Build.VERSION.SDK_INT >= 24) {
// For android N you need to use the file provider
return FileProvider.getUriForFile(this, getResources().getString(R.string.file_provider_name), getOutputMediaFile());
} else {
return Uri.fromFile(getOutputMediaFile());
}
}
/**
* returning file to store image / video
*/
private File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"DirectoryNameWhereYouWantToStore");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".mp4");
}
I found it's a common problem with capturing photo and receiving full size photo instead of thumbnail (according to: http://developer.android.com/training/camera/photobasics.html ). Taking photo and receiving thumbnail is easy, but rest of tutorial seems to be uncomplete and not working. Anyone resolved it in easy way?
public class TakePhoto extends Activity{
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
private String mCurrentPhotoPath;
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.take_photo);
mImageView = (ImageView) findViewById(R.id.imageView);
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i("ASD", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
}
04-25 18:01:14.239 17281-17281/com.(package).bazaar E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.(package).bazaar, PID: 17281
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.(package).bazaar/com.(package).bazaar.TakePhoto}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3626)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3669)
at android.app.ActivityThread.access$1300(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1341)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.klangstudios.bazaar.TakePhoto.onActivityResult(TakePhoto.java:46)
at android.app.Activity.dispatchActivityResult(Activity.java:6161)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3622)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3669)
at android.app.ActivityThread.access$1300(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1341)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
I would not expect data to be null there. However, there should not be any extras on that Intent. You only look for the "data" extra if you are not specifying EXTRA_OUTPUT. If you are specifying EXTRA_OUTPUT, you go get the photo from the path that you provided in EXTRA_OUTPUT, and you ignore the Intent delivered to onActivityResult().
With regards to the null data Intent itself, that may be something peculiar to the camera app that you are using. Please bear in mind that using ACTION_IMAGE_CAPTURE means that you are relying upon a third-party app to take the picture, and third-party apps can have bugs.
This may help: Android Camera Intent: how to get full sized photo?
Although what is doing is reading the file you create before launching camera intent, not reading data
I struggled hours on the same problem than "jean d'arme", except that I was seeking to get URI and not Bitmap. To spare other users this waste of time, I will highlight the clarifications of "jean d'arme" and "Felipe Augusto" that helped me solved the error, with the below steps :
1) Add a global variable in your class
private Uri uri;
2) Use this variable to get the content of photoURI inside dispatchTakePictureIntent()
private void dispatchTakePictureIntent() {
{...}
if (photoFile != null) {
uri = photoURI;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
3) Use this Uri in the onActivityResult method for whatever task you aim to
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
//Perform any task using uri
//For example set this URI to fill an ImageView like below
this.imageView.setImageURI(uri);
}
}
I hope this highlight will help some of you !