onActivityResult returned from a camera, Intent null - android

I follow the instruction on Camera on Android dev site
I just start the Camera Intent, not build my own camera.
The sample code to handle result return after taking a photo is as follows.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Video saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
}
}
}
resultCode is OK, but data is always NULL, which causes a NPE. I looked into the sdcard, the photo was really saved there. Any tip? tks much.
Update: logcat info as requested:
01-28 19:39:00.547: ERROR/AndroidRuntime(24315): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to resume activity {com.example.CameraTest/com.example.CameraTest.MyCamera}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.example.CameraTest/com.example.CameraTest.MyCamera}: java.lang.NullPointerException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2455)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2483)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1997)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3362)
at android.app.ActivityThread.access$700(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1162)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.example.CameraTest/com.example.CameraTest.MyCamera}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:2991)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2442)
... 13 more
Caused by: java.lang.NullPointerException
at com.example.CameraTest.MyCamera.onActivityResult(MyCamera.java:71)
at android.app.Activity.dispatchActivityResult(Activity.java:4654)
at android.app.ActivityThread.deliverResults(ActivityThread.java:2987)
... 14 more

The problem with your code is this:
data.getData()
This call does not get the extra with the key "data" from the returned Intent. It gets the field data from the returned Intent which is probably null.
You need to get the extra from the returned Intent like this:
data.getExtras().get("data");
Some of the other answers have indicated this, embedded in tons of other code. That makes it difficult to actually see what the problem is.

Here is the answer from a similar question. It seems like it might be a problem with Samsung phones...
Basically, if you have code like this which creates the Intent:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Then, in onActivityResult, replace data.getData() with fileUri.toString() and it will solve your problem.

Use #KJ50's solution, and use savedInstanceState to make sure you don't get a null.
/**
* 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 screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}

Try out below code :
Button m_btnCamera;
ImageView m_ivCaptureImage;
String m_curentDateandTime;
String m_imagePath;
Bitmap m_bitmap;
//Start camera to caputre image.
Intent m_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
m_intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
startActivityForResult(m_intent, TAKE_PHOTO_CODE);
private Uri getImageUri() throws CustomException
{
Uri m_imgUri = null;
File m_file;
try
{
SimpleDateFormat m_sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
m_curentDateandTime = m_sdf.format(new Date());
m_imagePath = File.getPath() + File.separator + m_curentDateandTime + ".jpg";
m_file = new File(m_imagePath);
m_imgUri = Uri.fromFile(m_file);
}
catch (Exception p_e)
{}
return m_imgUri;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK)
{
m_bitmap = ImageHelper.scaleImage(m_imagePath, 200, 200);
m_bitmap = ImageHelper.rotateImage(m_bitmap, true, m_rotate);
m_ivCaptureImage.setImageBitmap(m_bitmap);
}
}
}

Try this
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE_ID:
Bitmap bitmap = ImagePicker.getImageFromResult(this.getActivity(), resultCode, data);
if(data!=null){
//set image view
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}

This code will help you
The getData() method returns data only if Android version is newer than M, else it will return null result.
if (resultCode == Activity.RESULT_OK) {
//Check Android version, as intent.getData() will return data only if v is above or equal to M otherwise the data will be null
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
Uri selectedImageURI = imageReturnedIntent.getData();
Toast.makeText(getActivity(), "URI Path:" + selectedImageURI, Toast.LENGTH_LONG).show();
} else {
Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), photo, "Title", null);
Uri selectedImageURI = Uri.parse(path);
Toast.makeText(getActivity(), "URI Path:" + selectedImageURI, Toast.LENGTH_LONG).show();
}
}

Try this code below.....
btn_capture.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(photo);
}
}
}
Then finally you add below code to your manifest
<uses-feature android:name="android.hardware.camera"></uses-feature>

Related

onActivityResult returns null Intent

I am trying to capture image from camera. But it returns null Intent onActivityResult .
Here is my code
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
And onActivityResult is
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 7 && resultCode == RESULT_OK) {
try {
if(data.getData() == null) {
bitmap = (Bitmap)data.getExtras().get("data");
} else {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
ImageViewHolder.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am new to Android so please explain answer in detail.
Thanks in advance..!
Start Your work by passing intent through this :
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), 100);
so after capturing the image from camera use to get data about images through intent :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri yourCapturedImage = intent.getData();
}
Make sure you have added camera permissions, write permissions in manifest and also cross verify run time permissions.
Use your Intent like below, and specify the path where captured image will be write -
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputUri = Uri.fromFile("path of your directory");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
startActivityForResult(intent, 7);
You can also use setImageURI() in onActivityResult() instead of setImageBitmap()
First of all add the camera permissions in android manifest. If your android version is greater than lollipop then you need to add run time permissions See documentations here
<uses-permission android:name="android.permission.CAMERA"/>
and then your code will be
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
and then use setImageUrI() in your onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case 7:
/*case 7 for image results and display image in imageview via Uri*/
if (resultCode == RESULT_OK)
{
Uri imageUri = data.getData();
ImageViewHolder.setImageURI(imageUri);
}
return;
default:
return;
}
}
Uri imageUri = data.getData() will no more work..
first get bitmap from data like this:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
val imageBitmap = data.extras.get("data") as Bitmap
imageView.setImageBitmap(imageBitmap)
}
}
then save bitmap image.. please find details here:
https://developer.android.com/training/camera/photobasics

How can I get the URI with a custom camera in Android?

I'm switching from using the default camera to finally growing a pair and deciding to make a custom camera. It's only showing me how much I don't fully understand.
Here is basically way I have been doing things in the main activity as far as photos go, but it will no longer work:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_PHOTO_REQUEST) {
if (data == null) {
Toast.makeText(this, "General Error!", Toast.LENGTH_LONG).show();
}
else {
mMediaUri = data.getData();
}
Log.i(TAG, "Media URI: " + mMediaUri);
}
else {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(mMediaUri);
sendBroadcast(mediaScanIntent);
}
(...)
Here is the picture saving function along with a couple others of the new camera:
(...)
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("Picture taken");
String path = savePictureToFileSystem(data);
setResult(path);
finish();
}
private static String savePictureToFileSystem(byte[] data) {
File file = getOutputMediaFile();
saveToFile(data, file);
return file.getAbsolutePath();
}
private void setResult(String path) {
Intent intent = new Intent();
intent.putExtra(EXTRA_IMAGE_PATH, path);
setResult(RESULT_OK, intent);
}
*Credit to Paul Blundell
(...)
What do I need to do so that the main activity can receive the image's URI in the onactivityresult instead of the path String? Are URIs even applicable when it comes to custom cameras?
Please and thanks.
You use custom camera, but want to do it via Intent? OK, you have the absolute file path in
String abspath = data.getExtras().getString(EXTRA_IMAGE_PATH);
mMediaUri = Uri.fromFile(new File(abspath));

Android Application crash - Null Pointer Exception

I'm developing a simple app which captures an image from camera and saves it to storage. I cannot figure out what is wrong here...when user takes a picture and accept it, the app crashes.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try {
File f = createImageFile();
photoFile = Uri.fromFile(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
photoFile);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
Button saveButton = (Button) this.findViewById(R.id.button3);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
save2Samba("hello", "kfir.txt");
//Your code goes here
}
catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(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;
}
logcat says
12-29 18:01:20.893: E/AndroidRuntime(8026): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example.hofyam/com.example.hofyam.MainActivity}: java.lang.NullPointerException
Please help..I'm stuck. Thanks
who=null, request=1888, result=-1, data=null
data is null, meaning that the intent you recieved from the finishing activity is null. So calling : data.getExtras() will cause a NPE.
You have to test first if data is not null, like this :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if(data != null) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
EDIT:
If image is not created, may be it's due to your if test, meaning that data is still null. You have to set data values in your finishing activity :
Intent intent = getIntent().putExtra("data", "your data value");
in order to get them back in onActivityResult method :
data.getExtras().getString("data");
The problem is here, The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.
You should take care of the fields that can return null i.e. data and resultCode.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_CANCELED)
{
if (requestCode == CAMERA_REQUEST) {
if (data != null){
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
}

Android APP crashing (After Taking Picture from camera)

I have started Camera from my APP. Sometimes my App is crashed when my App is resumes after capturing image. And my APP is relaunched again.
What can I do to handle this type of crash.
public void onClick(View view)
{
// TODO Auto-generated method stub
if(view==btnAddPrescription)
{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo=getOutputMediaFile(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
Log.v("Image URI", imageUri.toString());
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.v("requestCode",requestCode+"");
Log.v("resultCode",resultCode+"");
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
selectedImageUri = imageUri;
newPictPath=selectedImageUri.getPath();
this.setSelectedPath(newPictPath);
Log.v("newPictPath",newPictPath);
getContentResolver().notifyChange(selectedImageUri, null);
ImageView imageView = (ImageView) findViewById(R.id.img_prescription);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try
{
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImageUri);
imageView.setImageBitmap(bitmap);
//Toast.makeText(this, selectedImageUri.toString(),Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.e("Camera", e.toString());
}
}
else if (resultCode == RESULT_CANCELED)
{
// User cancelled the image capture
}
else
{
// Image capture failed, advise user
}//else ends here
}//if ends here
}
I'm using this code. It works properly on Emulator. But, when I run it on device then Sometimes it crashes by throwing java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity this Exception.

Intercepting onActivityResult() for Camera application on Android

In my application, I'm trying to make it so the User can press a button, which will allow them to take a picture using the stock camera application on their phone.
I am following the guide to using an external Camera app to capture images that I can use in my own app from the Android Developers Guide (http://developer.android.com/guide/topics/media/camera.html#intent-receive)
I'm having trouble with the onActivityResult() method, it apparently takes in 3 parameters
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
Log.w("borre","Image saved to:\n" + data.getData());
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
But at the moment, the data Intent is coming back as null, so calling any methods on the Intent parameter throws a NullPointerException
Here's the code I'm using to call up the Camera application (It's basically the same as the code in the guide)
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Has anyone had this problem or knows why this Intent is coming back as null?
your are getting data part null bez you are not setting intent.setDataAndType() when you are starting Acitivty.like
public static final String IMAGE_UNSPECIFIED = "image/*";
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
startActivityForResult(intent, 3);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 0)
return;
if (requestCode == 2) {
Uri uri=data.getData(); //YOU GET DATA HERE
}
//OR
if (requestCode == 3) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)????
imageView.setImageBitmap(photo);
}
}
or in your case getting image path use:
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
//pic path
File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
}

Categories

Resources