Handle the Camera in a Fragment - android

Excuse me for any grammatical errors.
I would like to use the camera in a different activity than mainActivity.
I found this simple tutorial on google Taking Photos Simply, that says I have to use this function:
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
But, this function works fine only into the MainActivity, in fact, if I put this code in a different activity I get this error:
Cannot resolve method 'getPackageManager()'.
Some ideas?
Thank you!

Try out the following code:
static final int REQUEST_IMAGE_CAPTURE = 1;
Context c;
private void dispatchTakePictureIntent() {
Fragment yourFragment = this;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
yourFragment.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
Override your parent Activity's onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
Then add this to your fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK) {
//Do something with your captured image. EX:-
try {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath))
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}

Excuse me, I don't know why, when I try this application on my Nexus 5X, the photo lose the quality when it appears into the ImageView. Application image (Image View): i.imgur.com/VunFaHF.png?1 Camera Image: i.imgur.com/wjJ2a4w.jpg

Related

No callback (onActivityResult) from startActivityForResult

I'm trying to include functionality in an app for taking photos. The camera activity comes up, I can take a photo and tap the checkmark for using the photo just taken, but the app never receives it because onActivityResult is never called.
Here is the code that activates the camera activity:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
REQUEST_IMAGE_CAPTURE is set to 1.
The onActivityResult method that is never called looks like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...
}
The app has only one activity, the main activity.
I have tried different settings in the manifest, with no luck.
As noted here you have to add this in the manifest.
Once this is added:
<uses-feature android:name="android.hardware.camera"
android:required="true" />
After you took the photo and accept it, the callback is called
<uses-feature
android:name="android.hardware.camera"
android:required="false"/>
private Uri mCapturedImageURI;
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, System.currentTimeMillis() + "PRESCRIPTION");
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intentPicture, 1);
public String getCameraPathFromURI(Uri contentUri) {
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
return "";
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
if (mCapturedImageURI != null) {
realImagePath = getCameraPathFromURI(mCapturedImageURI);
}
}
break;
}

Get image from gallery to set in imageview in fragment? [duplicate]

This question already has answers here:
onActivityResult is not being called in Fragment
(41 answers)
Closed 7 years ago.
How to get image from gallary to set in Imageview in fragment ? onActivityResult not called in fragment..this the code i wrote in fragment
img_user.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
img_user.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close`enter code here`();
} else {
Toast.makeText(getActivity(), "Try Again!!", Toast.LENGTH_SHORT)
.show();
}
}
You can do this in this way....in your main activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//call super
super.onActivityResult(requestCode, resultCode, data);
}
and inside your fragment
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// ******** code for crop image
i.putExtra("crop", "true");
i.putExtra("aspectX", 100);
i.putExtra("aspectY", 100);
i.putExtra("outputX", 256);
i.putExtra("outputY", 356);
try {
i.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(i, "Select Picture"), 0);
}catch (ActivityNotFoundException ex){
ex.printStackTrace();
}
and
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0 && resultCode == Activity.RESULT_OK){
try {
Bundle bundle = data.getExtras();
Bitmap bitmap = bundle.getParcelable("data");
img_user.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Works perfect for me
I was also facing the same problem. Actually callback for startActivityForResult() is coming back to parent activity so you need to make
explicit call from fragment to onActivityResult() function as follows.
In Parent Activity class, override the onActivityResult() method and even override the same in Fragment Class and call as the following code.
In Parent Class:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = getFragmentManager().findFragmentById(R.id.container);
fragment.onActivityResult(requestCode, resultCode, data);
}
In Child Class:
That Extends fragment perform your logic for image setting on imageview.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
image.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
} else {
Toast.makeText(getActivity(), "Try Again!!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
Please find the following code, it will work. Add this in your fragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//Your stuff
}

OnActivityResults in fragment not called

UPDATE:
I have restarted my device, and it works now. Like a magic!!
ORIGINAL QUESTION:
I have read many answers for my question, but i still can't get a solution for my problem:
I had 1 fragment that opened an intent for capturing a photo and in the fragment I had the method OnActivityResults and all worked fine.
Now, I added 2nd fragment that also calls an intent with the same code (but different request code). I'm not sure that this cause the problem, but now, when I push the "V" that approve the captured photo, I'm getting back to different fragment and the OnActivityResults method isn't called.
In the fragment:
private static final int REQUEST_TAKE_PHOTO_CODE = 11;
private static final int REQUEST_ATTACH_PHOTO_CODE = 22;
takePhotoButton = (ImageButton)rootView.findViewById(R.id.imageButtonTakePhoto);
takePhotoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(MainActivity.deviceHasCamera){
Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoIntent, REQUEST_TAKE_PHOTO_CODE );
}
else{
Toast.makeText(activity, "No camera detected", Toast.LENGTH_SHORT).show();
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("EB", "onActivityResult CarAccident");
switch (requestCode) {
case REQUEST_TAKE_PHOTO_CODE:
//This case is when the user decide to Approve the captured photo
if (resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
Log.d("EB", "BitMap = " + photo.toString());
}
break;
case REQUEST_ATTACH_PHOTO_CODE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
Log.d("EB", "Uri fata.getData() = " + data.getData().toString());
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = this.activity.getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
photo = BitmapFactory.decodeFile(filePath);
//For the case that is Android 5.0 and the photo is on the server
// and not on the device
if (photo == null){
try {
photo = getBitmapFromUri(data.getData());
Log.d("EB", "photo = getBitmapFromUri(data.getData()) = " + photo.toString());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this.activity, FAILD_TO_ATTACH_PHOTO_MESSAGE,
Toast.LENGTH_SHORT).show();
}
}
//Set the photo to the imageView
imageView.setImageBitmap(photo);
Log.d("EB", "attached image = " + ((photo != null) ? photo.toString() : "NULL"));
}
break;
}
}
I tried to to write in the host Activity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
But it's not working. Hope you can help.
Thanks in advance!
You cant do this.
You must call it in your Activity and check if the result true with REQUEST_CODE. If equeals with your code, you must retrieve your data from method and do what you need. This is origin solution.

File path from Camera Intent

I'm trying to get the file path of pictures that I took with Camera Intent as a String, but the String filePath is always null. What am I doing wrong?
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnImageCapture:
Intent openCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(openCamera, OPEN_CAMERA);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case OPEN_CAMERA:
if (resultCode == RESULT_OK && data != null) {
Uri captureImage = data.getData();
String filePath = captureImage.getPath();
break;
}
}
}
This is how I get the image that was taken with the camera.
I create the file before and when the image gets saved then it gets saved to my file..
File externalFile = new File("Whatever you want the path to be...");
Uri uriSavedImage=Uri.fromFile(externalFile);
Intent launchcameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
launchcameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(launchcameraIntent,CAMERA_PIC_REQUEST);
Then when the result is received.
protected void onActivityResult(int requestCode,int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap photo = BitmapUtils.decodeFileForDisplay(new File("Whatever your file's path is");
}
}
}
try the following passing your captureImage Uri as parameter:
public String getRealPathFromURI(Uri contentUri) {
String[] projx = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, projx, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
EDIT:
that is a common bug that getData() returns null on some devices. You need to use a pre-inserted Uri to prevent that. Example:
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
preinsertedUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
Getting the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CAMERA_PIC_REQUEST:
if (resultCode != 0 && data != null) {
Uri imageUri = preinsertedUri;
}
break;
}

Insert an Image from the gallery on a button in Android

Im trying to do this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmp = BitmapFactory.decodeFile(picturePath);
b[1].setCompoundDrawablesWithIntrinsicBounds(null, new BitmapDrawable(bmp), null, null);
}
But it wont set the image, no matter what. I have tried several different methods too, like using an imagebutton instead of a button and using:
imageButton.setImageBitmap(bmp)
The gallery opens fine and and the callback comes to onActivityResult(...)
but the image wont appear on the button, I have an array of buttons.
I made a rapid test. The following code works for me. If with this you still can't set the image I would check if there's a layout problem (i.e. the image is set but there's no room to show it).
activity_main.xml has just an ImageButton set to wrap_content, inside the main layout which is match_parent.
public class MainActivity extends Activity {
ImageButton imgButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgButton = (ImageButton) findViewById(R.id.imgButton);
imgButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_CANCELED) return;
ParcelFileDescriptor fd;
try {
fd = getContentResolver().openFileDescriptor(data.getData(), "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
Bitmap bmp = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
imgButton.setImageBitmap(bmp);
}
}

Categories

Resources