onActivityResult is not calling after taking camera picture - android

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.

Related

Image Saved to Gallery After Being Captured

Hy,,, this has been confused me for a while since what I intended to do with my app was just to capture images and upload it without saving it into the gallery. But what happen is the opposite.
This is how I call the camera function
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_01);
And this is how I handle the request
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode == CAMERA_01){
if(resultCode == Activity.RESULT_OK){
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream output = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
byte[] byte_arr = output.toByteArray();
i11a1 = Base64.encodeToString(byte_arr, Base64.DEFAULT);
((SiteBefore)getActivity().getApplication()).seti11a1(i11a1);
BitmapDrawable ob = new BitmapDrawable(getResources(),bitmap);
img11a1.setBackgroundDrawable(ob);
}else if(resultCode == Activity.RESULT_CANCELED){
}
}
}
This code is written inside the fragment class. This cause the image being saved into the gallery. Anyone know what causes this?

Capture image from camera return low quality image

I've been developed app to take a picture to be saved in gallery. I've searched online and the easiest way that I could practice was to use data.getExtras().get("data") . So below are the code to take picture from camera. Note that I'm using fragment in this class.
img22a1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_01);
}
});
Get the captured image and convert it to string
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_01) {
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream output = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
byte[] byte_arr = output.toByteArray();
((SiteProgress) getActivity().getApplication()).seti22a1(Base64.encodeToString(byte_arr, Base64.DEFAULT));
BitmapDrawable ob = new BitmapDrawable(getResources(), bitmap);
img22a1.setBackgroundDrawable(ob);
} else if (resultCode == Activity.RESULT_CANCELED) {
}
}
}
I save the string into global variable so another activity can access it.
In another activity, I have a button to save the image into folder/gallery by accessing the image string.
for(int i=0;i<=namefile.length;i++){
Bitmap[] bitmap = new Bitmap[namefile.length];
FileOutputStream outputStream = new FileOutputStream(String.valueOf(namefile[i]));
bitmap[i] = BitmapFactory.decodeByteArray(decodedString[i],0,decodedString[i].length);
bitmap[i].compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), namefile[i].getAbsolutePath(), namefile[i].getName(), namefile[i].getName());
}
It worked to save the image into folder/gallery....But the quality of image was very low...I could barely see text in the image.
They said data.getExtras().get("data") supposed to return thumbnail and not the actual image. What I want here is to get the full image and not the thumbnail one.
Any answer will be very appreciated.
From: Android - How to get the image using Intent data
if(data != null)
{
Uri selectedImageUri = data.getData();
filestring = selectedImageUri.getPath();
Bitmap thumbnail = BitmapFactory.decodeFile(filestring, options2);
System.out.println(String.format("Bitmap(CAMERA_IMAGES_REQUEST): %s", thumbnail));
System.out.println(String.format("cap_image(CAMERA_IMAGES_REQUEST): %s", cap_image));
cap_image.setImageBitmap(thumbnail);
}

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

Take photo from camera in fragment

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();
}
}

save image from bytes returned from android camera intent is saved as small image

I am trying to capture an image using Android Camera Intent. Camera intent returns Byte Array and when I saved the byte array as a Bitmap, I am getting a very small image instead of getting an Image based on current camera settings (1024 Pixels currently set in the android mobile camera).
Usally i will get file path from the camera intent but somehow i am not getting from this device, so i am creating the bitmap from the byte returned by camera intent.
Anybody knows why is this and how to solve this issue. Thanks.
The below is the java code block I am using.
private Intent cameraIntent = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
if ( data != null)
{
Bitmap myImage = null;
Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100,stream);
byte[] byteArray = stream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
myImage = BitmapFactory.decodeByteArray(byteArray, 0,byteArray.length, options);
fileOutputStream = new FileOutputStream(sPath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
myImage.compress(CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
}
}
}
}
The data.getExtras("data") only returns a thumbnail image. To obtain the full-sized image, you need to pass the camera intent a file in which to store that image and later retrieve. A rough example follows.
Start the intent:
File dir = new File(Environment.getExternalStorageDirectory() + "/dcim/myappname");
File mFile = File.createTempFile("myImage", ".png", dir);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
Inside onActivityResult:
if (resultCode == RESULT_OK) {
Bitmap bm = BitmapFactory.decodeFile(mFile.getAbsolutePath());
}
// do whatever you need with the Bitmap
Keep in mind that mFile will have to be global or somehow persisted so that it may be called upon where necessary.

Categories

Resources