Take photo from camera in fragment - android

In my Fragment I try to take picture from my camera but the onActivityResult of my Fragment is not called. After taking photo this Fragment is not showing and is switching to my first Fragment. In there any other way for capturing photos in a Fragment, or what am I doing wrong?
Here is my current code:
public void takePhoto() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
PhotosListFragment.this.startActivityForResult(intent, 100);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 100:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getActivity().getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getActivity().getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
viewHolder.imageView.setImageBitmap(bitmap);
Toast.makeText(getActivity(), selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity(), "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}

Hope this will help you:
public class CameraImage extends Fragment {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
Button button;
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.camera_image,
container, false);
button = (Button) rootView.findViewById(R.id.button);
imageView = (ImageView) rootView.findViewById(R.id.imageview);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
imageView.setImageBitmap(bitmap);
}
}
}
}

This is one of the most popular issue. We can found lots of thread regarding this issue. But none of them is useful for ME.
So I have solved this problem using this solution.
Let's first understand why this is happening.
We can call startActivityForResult directly from Fragment but actually mechanic behind are all handled by Activity.
Once you call startActivityForResult from a Fragment, requestCode will be changed to attach Fragment's identity to the code. That will let Activity be able to track back that who send this request once result is received.
Once Activity was navigated back, the result will be sent to Activity's onActivityResult with the modified requestCode which will be decoded to original requestCode + Fragment's identity. After that, Activity will send the Activity Result to that Fragment through onActivityResult. And it's all done.
The problem is:
Activity could send the result to only the Fragment that has been attached directly to Activity but not the nested one. That's the reason why onActivityResult of nested fragment would never been called no matter what.
Solution:
1) Start Camera Intent in your Fragment by below code:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Fragment frag = this;
/** Pass your fragment reference **/
frag.startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); // REQUEST_IMAGE_CAPTURE = 12345
2) Now in your Parent Activity override **onActivityResult() :**
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
You have to call this in parent activity to make it work.
3) In your fragment call:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
// Do something with imagePath
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageview.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri selectedImage = getImageUri(getActivity(), photo);
String realPath=getRealPathFromURI(selectedImage);
selectedImage = Uri.parse(realPath);
}
}
}
4) Reference methods for getting URI:
-> Method for getting Uri from the Bitmap
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
-> Method for getting File path from the Uri
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
That's it.
With this solution, it could be applied for any single fragment whether it is nested or not. And yes, it also covers all the case! Moreover, the codes are also nice and clean.

I tried your code its working fine dude. I changed
PhotosListFragment.this.startActivityForResult(intent, 100);
to
getActivity().startActivityForResult(intent, 100);
which after taking the picture, returning back to same activity.
I think both of your fragments are on same activity.
if that is the situation, I suggest you to create a new activity and put the new fragment in there.

For Fragment this is simplest solution:
cameraIamgeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
getActivity().startActivityFromFragment(PlaceOrderFragment.this, cameraIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
// super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK && data != null) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
/*
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
*/
cameraIamgeView.setImageBitmap(bmp);
}
}
}catch(Exception e){
Toast.makeText(this.getActivity(), e+"Something went wrong", Toast.LENGTH_LONG).show();
}
}

Related

Intent not working in onActivityResult

I am trying to get image from gallery from my 1st Activity and want the resulted image in the ImageView of second activity.
Here is the Code For 1st Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageVew = (ImageView) findViewById(R.id.imageView);
}
public void useGalleryMethod(View view) {
//this is for picking Image from Gallery or file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
onActivityResult() in 1st Class:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
if (requestCode == 0 && resultCode == RESULT_OK && data != null) {
try {
//this is for picking Image from Gallery or file
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
imageVew.setImageBitmap(bitmap);
Intent intent = new Intent(MainActivity.this,ImageViewActivity.class);
intent.putExtra("Bitmap",bitmap);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
The Code For Second Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_view);
Intent getIntentInfo = getIntent();
if(getIntentInfo != null){
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Bitmap bitmap = (Bitmap) getIntentInfo.getParcelableExtra("Bitmap");
imageView.setImageBitmap(bitmap);
}else{
return;
}
}
The App is running properly and showing the gallery image in ImageView of 1st Class Only and not going to 2nd Activity using the Intent in onActivityResult method.
Please Let Me know whats wrong with my code? ?
or is there any other way and I am not going in the right direction ?
Use this method which is more convenient that Parcelable you used:
method 1: Your can save that to sd card and retrieve.
OR
method 2:
Convert Bitmap to Byte Array:-
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Pass Byte Array with Intent:-
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);
Get Bitmap from ByteArray received in bundle:-
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bmp);
In onActivityResult() of first activity replace this -
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
if (requestCode == 0 && resultCode == RESULT_OK && data != null) {
try {
//this is for picking Image from Gallery or file
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
imageVew.setImageBitmap(bitmap);
// Send Image URI istead
Intent intent = new Intent(MainActivity.this,ImageViewActivity.class);
intent.putExtra("imageUri", data.getData().toString());
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
And on Second Activity do something like -
if(getIntentInfo != null){
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),
Uri.parse(getIntentInfo.getStringExtra("imageUri")));
imageVew.setImageBitmap(bitmap);
}else{
return;
}

Take picture with camera and send the path to other activity

I'm working on my app in Android and I'm having a little problem. On my MainActivity I take a picture and then save the path in a String, then I send this string to CameraActivity. This is my code:
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri tempUri = getImageUri(getApplicationContext(), photo);
String ruta = getRealPathFromURI(tempUri);
Intent i = new Intent(getApplicationContext(), WarikeActivity.class);
i.putExtra("ruta",ruta);
startActivity(i);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Then, on CameraActivity I receive the path of the picture and Im trying this to put the picture on my ImageView
void events(){
Bundle extras = getIntent().getExtras();
ruta = extras.getString("ruta");
Bitmap imageBitmap = (Bitmap) extras.get(ruta);
imgWarike.setImageBitmap(imageBitmap);
}
But the Bitmap is null. Any idea why this happen? Thanks in advance.
Instead of taking picture and then get it path, first choose the path you want then save image there. take a look at below code:
private File file;
private URI imageUri;
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String name = String.valueOf(System.currentTimeMillis() + ".jpg");
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if (!file.exists()) {
file.mkdirs();
}
File photo = new File(file, name);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, CAMERA_REQUEST);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
imageUri = data.getData();
Intent i = new Intent(getApplicationContext(), WarikeActivity.class);
i.putExtra("ruta", file);
startActivity(i);
}
}
If you are trying to get the bitmap from the path obtained from intent use this code.
Bitmap myBitmap = BitmapFactory.decodeFile(<yourFilepath>);
Or as you already obtained bitmap in your first activity, you directly send bitmap through intent as follows.
https://stackoverflow.com/a/2459624/5577385
You can do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent i = new Intent(getApplicationContext(), WarikeActivity.class);
i.putExtra("foto", byteArray);
startActivity(i);
}
And then:
void events(){
byte[] byteArray = getIntent().getByteArrayExtra("foto");
Bitmap foto = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imgFoto.setImageBitmap(foto);
}
Have you tried to follow the official Android documentation about it ? http://developer.android.com/training/camera/photobasics.html

Android: How to set the photo selected from gallery to a bitmap

I am asking the user for the access to the gallery through the code as a listener here:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
However, I am confused as to how I would set a variable to the photo selected.
Where would I put the code to set a variable as the photo selected?
Thanks :)
First you have to override onActivityResult to get the uri of the file selected image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == SELECT_PHOTO) {
if (resultCode == RESULT_OK) {
if (intent != null) {
// Get the URI of the selected file
final Uri uri = intent.getData();
useImage(uri);
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
Then define useImage(Uri) to use the image
void useImage(Uri uri)
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
//use the bitmap as you like
imageView.setImageBitmap(bitmap);
}
You can do it like this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
Alternative for Akash Kurian Jose answer
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
I always use
fun getBitmap(file: Uri, cr: ContentResolver): Bitmap?{
var bitmap: Bitmap ?= null
try {
val inputStream = cr.openInputStream(file)
bitmap = BitmapFactory.decodeStream(inputStream)
// close stream
try {
inputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}catch (e: FileNotFoundException){}
return bitmap
}
It works both for photos from gallery and photos from camera.
Larger issue about it: Picasso unable to display image from Gallery
Open Gallery using this method:
private void openGallery(){
if (Build.VERSION.SDK_INT <19){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_picture)),GALLERY_INTENT_CALLED);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
}
}
Then you are able to read convert Uri to Bitmap using afromentioned ContentResolver.openInputStream or set image ImageView.setImageUri(Uri)
If you want to display the selected image to any particular ImageView.
Suppose we have RC_PHOTO_PICKER = 1 then these lines of code should do the magic
private void openPhotoPicker() {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, false);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Complete Action Using"), RC_PHOTO_PICKER);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK && data != null) {
Uri pickedImage = data.getData();
//set the selected image to ImageView
mImageView.setImageURI(pickedImage);
}
}
And simply call the openPhotoPicker() method afterwards

How to Capture Image in Fragment Android

I am working with capturing an image and then show it on my ImageView in my fragment. I searched this through web and still I cannot make it.
Below is what I am doing.
btnCaptureImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1888);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("LOG", ""+requestCode);
if (requestCode == 1888 && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
super.onActivityResult(requestCode, resultCode, data);
}
The Logcat says 1888 only but the imageView did not load the image.
I also tried this
btnCaptureImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/ImagesFolder/");
folder.mkdirs();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
resultingFile = new File(folder.toString() + "/image.jpg");
Uri uriSavedImage=Uri.fromFile(resultingFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(cameraIntent, 1888);
}
});
But it throws exception:
E/AndroidRuntime(4824): java.lang.RuntimeException: Unable to resume activity {com.myapp.android/com.myapp.android.MyHomeActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=264032, result=-1, data=null} to activity {com.myapp.android/com.myapp.android.MyHomeActivity}: java.lang.NullPointerException
E/AndroidRuntime(4824): at com.myapp.android.MyFragment.onActivityResult(MyFragment.java:300)
Try putting
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, your_image_uri);
before this
startActivityForResult(cameraIntent, 1888);
I'm sorry mate but I can't seem to understand why it's giving that exception. Try this approach, it works for me.
Define the file globally and inside onActivityResult
if (requestCode == 1888 && resultCode == Activity.RESULT_OK) {
Bitmap photo = Media.getBitmap(getActivity().getContentResolver(), Uri.fromFile(resultingFile));
//Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
Check if your onActicityResult is beeing called. If not check:
onActivityResult is not being called in Fragment
First, in the fragment starts the intent to capture the image:
private void startIntentImageCapture() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile("imageName.jpg", ".jpg", storageDir);
path = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, path);
getActivity().startActivityForResult(cameraIntent, CAPTURE_IMAGE_REQUEST_CODE);
} catch (IOException e) {
e.printStackTrace();
}
}
path variable, must be an public static Uri instance. And another public static Integer for the request code: public static final Integer CAPTURE_IMAGE_REQUEST_CODE = 100;
Then in the Activity, read this path and decode the image:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == YourFragment.CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Bitmap imageBitmap = decodeFile(YourFragment.path);
//do something with your photo
}
}
}
I'm sure this is not the best and cleaner method but it works for me. Hope it helps!
EDIT
I forgot the code to decode the image.
public Bitmap decodeFile(Uri uriFile) throws OutOfMemoryError {
String filePath = uriFile.getPath();
BitmapFactory.Options bmOptions;
Bitmap imageBitmap;
try {
imageBitmap = BitmapFactory.decodeFile(filePath);
} catch (OutOfMemoryError e) {
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 4;
bmOptions.inPurgeable = true;
imageBitmap = BitmapFactory.decodeFile(filePath, bmOptions);
}
return imageBitmap;
}
The bmOptions ensure that OutOfMemoryError doesn't occurs.

onActivityResult is not calling after taking camera picture

I am doing an android app, in which I have a functionality that, I need to open camera and take a picture. After taking picture onActivityResult is not called. my screen remains only in camera state.
My code:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaFile = new File(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath());
Uri imageUri = Uri.fromFile(mediaFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 1);
onActivityResult code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && !data.toString().equalsIgnoreCase("Intent { }"))
switch (requestCode) {
case 1:
Log.i("StartUpActivity", "Photo Captured");
Uri uri = data.getData();
String imgPath = getRealPathFromURI(uri);
bitmap = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
img1.setImageBitmap(bitmap);
}
}
onActivityResult is probably called, but the statements inside your if statement and switch/case statements are not being executed, because they are never reached.
The code below includes two methods takePhoto and onActivityResult, is very short and works perfectly. Take a look at it, it probably will help you!
public void takePhoto(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 == 1) {
photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
You can run your application in debug mode, after putting a breakpoint in onActivityResult method,
if it's stopping there after getting from the Camera then it's being called successfully.
and you could just change the if statement you're using making your code like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null && resultCode = RESULT_OK)
switch (requestCode) {
case 1:
Log.i("StartUpActivity", "Photo Captured");
Uri uri = data.getData();
String imgPath = getRealPathFromURI(uri);
bitmap = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
img1.setImageBitmap(bitmap);
}
}
and note that it is more recommended to using final ints as the request code instead of rewriting them everytime they're needed
like :
private final int START_CAMERA_REQUEST_CODE = 1;
I think this may be help you
Follow Below Code step by step and compare with your code to avoid null exception
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
1 OnActivity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1)
onCaptureImageResult(data);
}
}
2
onCaptureImageResult
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
Uri tempUri = getImageUri(getApplicationContext(), thumbnail); // call getImageUri
File finalFile = new File(getRealPathFromURI(tempUri));
file_path = finalFile.getPath().toString(); // your file path
imgview.setImageBitmap(thumbnail);
// this code will get your capture image bitmap}
3 getImageUri
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); // your capture image URL code
return Uri.parse(path);
}
Using this code your screen will not remain more on camera state it will finish and image will be load as well you get image URL.
Bitmap mBitmap = BitmapFactory.decodeFile(imgPath);
pass Image path which you create from URI.
Probably, your activity is reloaded after camera is finished, but your code is not prepared to such situation.
See Android startCamera gives me null Intent and ... does it destroy my global variable?.
I think onActivity is called but it doesn't go into the if condition
Check only for null in if condition:
if (data != null )
switch (requestCode) {
case 1:
Log.i("StartUpActivity", "Photo Captured");
Uri uri = data.getData();
String imgPath = getRealPathFromURI(uri);
bitmap = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
img1.setImageBitmap(bitmap);
}
From where you are calling startActivityForResult(intent, 1),
and where you Overriding onActivityResult() ?
I mean if you call startActivityForResult() from Frgment then you should override onActivityResult() in fragment it self, same applies to Activity also.

Categories

Resources