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.
Related
Hi I want to capture image and do some opration for that image in my next activity.I have tried to run the below code in Samsung and Moto G and its working fine.When I tried same code with redmi note3,after Clicking right mark it is coming to the same activity.How to solve this? This is my code:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputFileUri = Uri.fromFile(originalFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No camera app found!", Toast.LENGTH_LONG).show();
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
Bitmap imageData = null;
if (resultCode ==Activity.RESULT_OK) {
try
{
BitmapFactory.Options bitopt=new BitmapFactory.Options();
imageData = BitmapFactory.decodeFile(imagePath, bitopt);
Uri tempUri = getImageUri(getApplicationContext(), imageData);
Intent i = new Intent(this, Image_R.class);
i.putExtra("imageUri", tempUri.toString());
startActivityForResult(i, 3);
}
catch (Exception e) {
Toast.makeText(this, "Unable to save image", Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
}
}
replace this:--
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
Add this code to your activity tag inside your Manifest file.
android:configChanges="orientation|keyboardHidden|screenSize"
It will not let your current activity to destroy and re-create so you will get the result.
And if this doesn't work make sure that your Device is not on power/battery saving mode.
RedMi devices with active power/battery saving mode cause previous activity to lose it's state and when coming back for result it will call onCreate again so you won't get the true result.
When I press the photoButton, the default Camera App starts.
My Problem is that it says, that the storage is full.
When I start the Camera app seperate the Error didn't show up.
Here is the Code for the Camera Intent:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CAMERA_PIC_REQUEST: {
try {
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.taskPhotoImage);
imageView.setImageBitmap(image);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
textField.setText(textField.getText() + " " + result.get(0));
}
break;
}
}
}
in onCreate() method:
photoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
I don't know if it's a problem within the code. But it looks like that something goes wrong
Kind Regards
Try This:-
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// After camera screen this code will excuted
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
output.setText("Video File : " +data.getData());
// Video captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Video saved to:" + data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
output.setText("User cancelled the video capture.");
// User cancelled the video capture
Toast.makeText(this, "User cancelled the video capture.",
Toast.LENGTH_LONG).show();
} else {
output.setText("Video capture failed.");
// Video capture failed, advise user
Toast.makeText(this, "Video capture failed.",
Toast.LENGTH_LONG).show();
}
}
}
try this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.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());
}
}
}}
And if you want camera intent
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "picture.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST);
}
/*
* 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", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/*
* Recording video
*/
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST)
{
if (resultCode == RESULT_OK)
{
// successfully captured the image
// display it in image view
this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
previewCapturedImage();
}
});
}
else if (resultCode == RESULT_CANCELED)
{
// user cancelled Image capture
Toast.makeText(getApplicationContext(),"User cancelled image capture", Toast.LENGTH_SHORT).show();
}
else
{
// failed to capture image
Toast.makeText(getApplicationContext(),"Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
this code is working on Google Nexus 4.4.4, but this same code is not working on Moto G 4.4.4.
I also used debugger but in the Moto G onActivityResult is not called.
Use this code:
ImageView profile=(ImageView)findviewById(R.id.imageview);
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, code);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == code) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
bmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(selectedImage));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
profile.setImageBitmap(bmp);
}
}
}
For working on all devices you don't have to put Extra in intent, and you need to get the path of image inside OnActivityResult method, Example:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
// retrieve the bitmap from the intent
bitmap = (Bitmap) data.getExtras().get("data");
Cursor cursor = getActivity().getContentResolver().query(Media.EXTERNAL_CONTENT_URI,new String[] {
Media.DATA,
Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION },
Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToFirst()) {
do {
Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
selectedImagePath = uri.toString();
} while (cursor.moveToNext());
cursor.close();
}
Log.e("path of the image from camera ====> ",selectedImagePath);
public void callCamera() {
//access to camara
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
I have an activity where click of button camera activity is launched . Sometimes onActivityResult is called and sometimes not . Even after restarting the device the onActivityResult is not called nor does it restart the current activity . Any solution to this weird behavior ?
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
String imageUri = data.toURI();
Uri uri = Uri.parse(imageUri);
try {
mBitmap = Media.getBitmap(getContentResolver(), uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// if result is ok returns the bitmap
// mBitmap = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(mBitmap);
new Thread(postTheImage).start();
} else {
Toast.makeText(getApplicationContext(), "Error during capturing the image", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.capture_image_button) {
// Open the camera to capture the image
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
You are not providing the camera activity with the information it requires. You need to supply it a file URI.
Please refer to the following
onActivityResult returned from a camera, Intent null
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>