I have an ImageView opens a dialog with 2 options
to select photo from External Memory
or take new one using Camera
it opens the dialog and the dialog takes permissions successfully then open the camera or memory
but it gives me an error when i select photo from the memory or approve taken photo by camera
I am using OnPhotoReceivedListener interface in the dialog fragment to retrieve the photo and imagePath
Here is How i call the Dialog from the Activity
public class EditNoteActivity extends AppCompatActivity implements ChoosePhotoDialog.OnPhotoReceivedListener{
private String mSelectedImagePath;
private static final int REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
mSelectedImagePath = null;
ImageView addImageIV = (ImageView) findViewById(R.id.ivAddImage);
addImageIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Make sure all permissions have been verified before opening the dialog
*/
for(int i = 0; i < Permissions.PERMISSIONS.length; i++){
String[] permission = {Permissions.PERMISSIONS[i]};
if(checkPermission(permission)){
if(i == Permissions.PERMISSIONS.length - 1){
Log.d(TAG, "onClick: opening the 'image selection dialog box'.");
ChoosePhotoDialog dialog = new ChoosePhotoDialog();
dialog.show(getSupportFragmentManager(), "ChoosePhotoDialog");
}
}else{
verifyPermissions(permission);
}
}
}
});
/**
* Retrieves the selected image from the bundle (coming from ChoosePhotoDialog)
* #param bitmap
*/
#Override
public void getBitmapImage(Bitmap bitmap) {
Log.d(TAG, "getBitmapImage: got the bitmap: " + bitmap);
//get the bitmap from 'ChangePhotoDialog'
if(bitmap != null) {
compressBitmap(bitmap, 70);
//TODO: Save Image and get It's Url
}
}
#Override
public void getImagePath(String imagePath) {
Log.d(TAG, "getImagePath: got the image path: " + imagePath);
if( !imagePath.equals("")){
imagePath = imagePath.replace(":/", "://");
mSelectedImagePath = imagePath;
mImgUrls += StringManipulation.imgSerialize(new String[]{imagePath, "Description"});
initRecyclerView(mImgUrls);
}
}
public Bitmap compressBitmap(Bitmap bitmap, int quality){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
return bitmap;
}
and Here is my Dialog class
public class ChoosePhotoDialog extends DialogFragment {
private static final String TAG = "ChoosePhotoDialog";
public interface OnPhotoReceivedListener{
public void getBitmapImage(Bitmap bitmap);
public void getImagePath(String imagePath);
}
OnPhotoReceivedListener mOnPhotoReceived;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_camera_or_memory, container, false);
//initalize the textview for starting the camera
TextView takePhoto = (TextView) view.findViewById(R.id.tvTakeCameraPhoto);
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: starting camera.");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, Permissions.CAMERA_REQUEST_CODE);
}
});
//Initialize the textview for choosing an image from memory
TextView selectPhoto = (TextView) view.findViewById(R.id.tvChoosePhotoFromMemory);
selectPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: accessing phones memory.");
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, Permissions.PICK_FILE_REQUEST_CODE);
}
});
// Cancel button for closing the dialog
TextView cancelDialog = (TextView) view.findViewById(R.id.tvCancelTakingPhoto);
cancelDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing dialog.");
getDialog().dismiss();
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
mOnPhotoReceived = (OnPhotoReceivedListener) getTargetFragment();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/*
Results when taking a new image with camera
*/
if(requestCode == Permissions.CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: done taking a picture.");
//get the new image bitmap
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: received bitmap: " + bitmap);
//send the bitmap and fragment to the interface
mOnPhotoReceived.getBitmapImage(bitmap);
getDialog().dismiss();
}
/*
Results when selecting new image from phone memory
*/
if(requestCode == Permissions.PICK_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Uri selectedImageUri = data.getData();
File file = new File(selectedImageUri.toString());
Log.d(TAG, "onActivityResult: images: " + file.getPath());
//send the bitmap and fragment to the interface
mOnPhotoReceived.getImagePath(file.getPath());
getDialog().dismiss();
}
}
}
And this is the Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65544, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:14786 flg=0x1 launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } }} to activity {com.ahmed_smae.everynote/com.ahmed_smae.everynote.EditNoteActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void com.ahmed_smae.everynote.Utils.ChoosePhotoDialog$OnPhotoReceivedListener.getImagePath(java.lang.String)' on a null object reference
Do you think the problem with the interface ?
How Can I solve it ?
The error is in your On your ActivityResult method. You are accessing a method on the interface of a null object.
Please set your debugger
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
mOnPhotoReceived = (OnPhotoReceivedListener) getTargetFragment();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
}
}
Then confirm the getTargetFragment() is working.
As I suspect that this is returning null or it is getting nulled out at some point before you are accessing it.
mOnPhotoReceived appears to be null in your error, so then you should set a breakpoint at the point of which you are calling getImagePath() and see the object is null. Next you just need to see where/how it is set to null.
Related
Hello I am trying to crop an image from android camera. I camera is activted and the activity to crop the image is also activated.
But, I am not being able to pass the cropped image to another activity.
I searched, I cant find a solution. What iam doing wrong? Maybe, It is because the putExtras?
lib page:
https://github.com/ArthurHub/Android-Image-Cropper
my PhotoFragment.java
public class PhotoFragment extends Fragment{
private static final String TAG = "PhotoFragment";
//constants
private static final int PHOTO_FRAGMENT_NUM = 1;
private static final int GALLERY_FRAGMENT_NUM = 2;
private static final int CAMERA_REQUEST_CODE = 5;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo, container, false);
Log.d(TAG, "onCreateView: Started.");
Button btnLaunchCamera = (Button) view.findViewById(R.id.btnLaunchCamera);
btnLaunchCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: launching the camera.");
// Create intent to Open Image
Intent galleryIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(galleryIntent, CAMERA_REQUEST_CODE);
}
});
return view;
}
private boolean isRootTask(){
if(((ShareActivity)getActivity()).getTask() == 0){
return true;
}else{
return false;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("APP_DEBUG", String.valueOf(requestCode));
try {
// When an Image is picked
if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
CropImage.activity(selectedImage)
.setGuidelines(CropImageView.Guidelines.ON)
.setMinCropResultSize(800, 800)
.setMaxCropResultSize(1000, 1000)
.start(getContext(), this);
}
// when image is cropped
else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Log.d("APP_DEBUG",result.toString());
if (resultCode == Activity.RESULT_OK) {
Uri resultUri = result.getUri();
Log.d("APP_DEBUG",resultUri.toString());
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), resultUri);
//pofilePic.setImageBitmap(bitmap);
Toast.makeText(getContext(), "sssss", Toast.LENGTH_SHORT).show();
if(isRootTask()) {
try {
Log.d(TAG, "onActivityResult: received new bitmap from camera" + bitmap);
Intent intent = new Intent(getContext(), NextActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
startActivity(intent);
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException" + e.getMessage());
}
}else {
try {
Log.d(TAG, "onActivityResult: received new bitmap from camera" + bitmap);
Intent intent = new Intent(getContext(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException" + e.getMessage());
}
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
else {
Toast.makeText(getActivity(), "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Something went wrong"+e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
and My NextActivity.java is:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mcaption = (EditText) findViewById(R.id.caption);
setupFirebaseAuth();
ImageView backArrow = (ImageView) findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the activity.");
finish();
}
});
TextView share = (TextView) findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
// upload the image to firebase
Toast.makeText(NextActivity.this,"Attempting to upload a new photo", Toast.LENGTH_SHORT).show();
String caption = mcaption.getText().toString();
// check if the intent came from gallery or from the camera
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl, null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null, bitmap);
}
}
});
setImage();
}
/**
* gets the image url from the incoming intent and displays the chosen image
*/
private void setImage(){
intent = getIntent();
ImageView image = (ImageView) findViewById(R.id.imageShare);
// check if the intent came from gallery or from the camera
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
Log.d(TAG, "setImage: got new image url: " + imgUrl);
// UniversalImageLoader handles null , oder wise we should check is image is null
UniversalImageLoader.setImage(imgUrl, image, null, mAppend);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
Log.d(TAG, "setImage: got new Bitmap");
image.setImageBitmap(bitmap);
}
}
I expect to get the cropped image in the ImageView image of the NextActivity.java
I am trying to use Ucrop from a fragment. The issue I am facing is that onActivityresult is not receiving requestCode == UCrop.REQUEST_CROP thus not performing the actions I need to do with the image. I have searched around for tutorials but I haven't managed to find any.
The following is the code of the fragment that is using UCrop:
public class FragmentSettingsTabImage extends Fragment {
private String TAG = "----->";
Tools t;
private String currentPhotoPath;
private final int REQUEST_TAKE_PHOTO = 1;
private final int CAMERA_PERMISSIONS = 2;
private ImageView imgTabImageDriver;
private Button btnSettingsSaveImage;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Objects.requireNonNull(getActivity()).finishAffinity();
}
});
builder.create().show();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.makeUcropOptions(Objects.requireNonNull(getActivity()));
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity());
}
Log.d(TAG, "onActivityResult: CCCCCCC" + resultCode + " " + requestCode);
// On result from cropper add to imageview
getActivity();
if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getActivity()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgTabImageDriver, new Callback() {
#Override
public void onSuccess() {
btnSettingsSaveImage.setEnabled(true);
}
#Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SharedPreferences preferences = Objects.requireNonNull(this.getActivity()).getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
View view = inflater.inflate(R.layout.fragment_settings_tab_image, container, false);
imgTabImageDriver= view.findViewById(R.id.imgTabImageDriver);
ImageView imgTakeSettingsDriverPicture = view.findViewById(R.id.imgTakeSettingsDriverPicture);
btnSettingsSaveImage = view.findViewById(R.id.btnSettingsSaveImage);
imgTakeSettingsDriverPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgTabImageDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnSettingsSaveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString("driver_picture", currentPhotoPath);
editor.apply();
}
});
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getContext()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
Log.d(TAG, "onCreateView: " + preferences.getString("driver_picture", ""));
builder.build().load(new File(preferences.getString("id_picture", ""))).into(imgTabImageDriver);
return view;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(Objects.requireNonNull(getActivity()).getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("IMAGE CREATION", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.mytestapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "didimage_" + timeStamp + "_";
File storageDir = Objects.requireNonNull(getActivity()).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
The same code from a normal activity works without any issues. Any help appreciated.
Managed to solve the issue. To pass the result of the UCrop activity to the fragment and not to the hosting activity you need to call the UCrop....start() method as follows:
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity().getApplicationContext(), getFragmentManager().findFragmentByTag("your_fragment_tag"));
so
.start(Context, Fragment)
This will make sure that the onActivityResult of the fragment gets called and not the one of the hosting activity.
This works also:
UCrop.of(sourceUri,destinationUri)
.withOptions(options)
.start(getActivity(),YourFragment.this);
If you want to start uCrop activity from Fragment use this.
UCrop.of(uri, destinationFileName)
.withAspectRatio(1, 1)
.start(getContext(), this, UCrop.REQUEST_CROP);
I'm using Picasso to get images from the gallery. I've followed a few Questions around the same topic on SO but haven't seemed to have fixed my issue. I got my file path from onActivityResult and tried adding the "file:" + .... + ".jpg" to the file and setting it to the ImageView. But it doesn't seem to be setting to it.
public class PictureDialog extends DialogFragment {
private ImageView imageView;
private RelativeLayout relativeLayout;
private Button saveMemory;
private Bitmap bitmap, bMapScaled;
private FinishedMemorySaving fMS;
public interface FinishedMemorySaving {
void showMemory(Memory memory);
}
public PictureDialog(){
}
public static PictureDialog newInstance(Memory memory){
PictureDialog pictureDialog = new PictureDialog();
Bundle args = new Bundle();
args.putString("title", memory.getTitleMem());
args.putString("desc", memory.getDescMem());
args.putDouble("lat", memory.getLocationMem().latitude);
args.putDouble("lng", memory.getLocationMem().longitude);
args.putString("date", memory.getFormatedDate());
pictureDialog.setArguments(args);
return pictureDialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.picture_dialog, container);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final String title = getArguments().getString("title");
final String desc = getArguments().getString("desc");
final double lat = getArguments().getDouble("lat");
final double lng = getArguments().getDouble("lng");
imageView = (ImageView)view.findViewById(R.id.memPic);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
}
});
saveMemory = (Button)view.findViewById(R.id.saveMemory);
saveMemory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Memory memory = new Memory();
memory.setTitleMem(title);
memory.setDescMem(desc);
memory.setLocationMem(new LatLng(lat, lng));
memory.setFormatedDate(new Date());
memory.setImageMem(bitmap);
try {
saveToCloud(memory);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK && data != null){
String path = data.getData().getPath();
File file = new File("file:" + String.valueOf(path) + ".jpg");
Log.i("FILE ERROR", "file:" + path + ".jpg");
setPicImage(file);
//imageView.setImageBitmap(bMapScaled);
}
}
public void setPicImage(File file){
if(file == null){
Log.i("FILE ERROR", "No file " + file.getPath());
} else {
// WHERE I WANT TO SET THE IMAGE TO FROM PICASSO
Picasso.with(getContext()).load(file).centerInside().fit().into(imageView);
}
}
.........
}
I get this when I print out the File Path when I added the "file:" etc:
file:/external/images/media/6854.jpg
Just hoping to find something that might help me set it to the ImageView. Thanks.
Threr is what i have done. On my activity. I take 2 picture correctly but if i change the orientation of the phone app crash
public class MyactivityTakePicture extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//initialisation
setContentView(R.layout.picture_main_layout);
img1 = (ImageView)findViewById(R.id.photo1);
img2 = (ImageView)findViewById(R.id.photo2);
//creation des dossiers
dir1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/g0/";
newdir1 = new File(dir1);
newdir1.mkdirs();
dir2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/g1/";
newdir2 = new File(dir2);
newdir2.mkdirs();
capture1 = (Button) findViewById(R.id.btnCapture1);
capture1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
takepicture1();
}
});
capture2 = (Button) findViewById(R.id.btnCapture2);
capture2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
takepicture2();
}
});
if(savedInstanceState != null){
filePath1 = savedInstanceState.getString("chemin1");
filePath2 = savedInstanceState.getString("chemin2");
bitmap1 = BitmapFactory.decodeFile(filePath1);
img1.setImageBitmap(bitmap1);
//filePath2 = savedInstanceState.getString("chemin1");
Log.w("A", ""+filePath1);
Log.i("F", ""+filePath2);
bitmap2 = BitmapFactory.decodeFile(filePath2);
img2.setImageBitmap(bitmap2);
}
}
//prise de photo N°1
..................
//prise de photo N°2
protected void takepicture2(){
//nom des photos photo1.jpg, photo2.jpg ...
count++;
file2 = dir2+"photo.jpg";
File newfile2 = new File(file2);
filePath2 = dir2+"photo.jpg";
try {
newfile2.createNewFile();
} catch (IOException e) {
Log.e("Error", e.toString());
}
Uri outputFileUri2 = Uri.fromFile(newfile2);
Intent cameraIntent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent2.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri2);
startActivityForResult(cameraIntent2, TAKE_PHOTO_CODE2);
}
//Enregistrement OK
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE1 && resultCode == RESULT_OK) {
Log.d("CameraDemo1", "Pic saved");
bitmap1 = BitmapFactory.decodeFile(filePath1);
img1.setImageBitmap(bitmap1);
}
if (requestCode == TAKE_PHOTO_CODE2 && resultCode == RESULT_OK){
Log.d("CameraDemo2", "Pic saved");
bitmap2 = BitmapFactory.decodeFile(filePath2);
img2.setImageBitmap(bitmap2);
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(newdir1==null){
newdir1 = new File(file1);
}// if
if(newdir2==null){
newdir2 = new File(file2);
}
outState.putString("chemin1", filePath1);
outState.putString("chemin2", filePath2);
}
}
First, Activity lauch correctely, take the two picture.
If i try to change orientation of my phone. She crash.
Please you see?
The problem is that your images aren't getting deallocated from memory.
java.lang.OutOfMemoryError: bitmap size exceeds VM budget
read this articles, would be helpful for you
http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html
http://androidactivity.wordpress.com/2011/09/24/solution-for-outofmemoryerror-bitmap-size-exceeds-vm-budget/
http://mobi-solutions.blogspot.mx/2010/08/how-to-if-you-want-to-create-and.html
UPDATE:
I have seen your code and i suggest the use of the method onDestroy() to set the bitmap instances to null:
#Override
protected void onDestroy(){
super.onDestroy();
bitmap1 = null;
bitmap2 = null;
}
I thought it was simple to capture camera image to a file, since there are many examples. But after tying a lot of them, I still not get it work.
My code is:
public class MyActivity extends Activity {
private Button btn;
private ImageView imageView;
private static final File photoPath = new File(Environment.getExternalStorageState(), "camera.jpg");
private static final int CAMERA = 1;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
setListeners();
}
private void setListeners() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoPath));
startActivityForResult(intent, CAMERA);
}
});
}
private void findViews() {
btn = (Button) findViewById(R.id.btn);
imageView = (ImageView) findViewById(R.id.imageView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA) {
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = getCameraBitmap(data);
if (bitmap == null) {
Toast.makeText(MyActivity.this, "Can't get bitmap from camera", Toast.LENGTH_LONG).show();
} else {
imageView.setImageBitmap(bitmap);
}
} catch (IOException e) {
Toast.makeText(MyActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
public Bitmap getCameraBitmap(Intent data) throws IOException {
if (data == null) {
// try solution 1
try {
return MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(photoPath));
} catch (FileNotFoundException e) {
return BitmapFactory.decodeFile(photoPath.getAbsolutePath());
}
} else {
Uri image = data.getData();
if (image != null) {
// try solution 3
InputStream inputStream = getContentResolver().openInputStream(image);
return BitmapFactory.decodeStream(inputStream);
} else {
// try solution 4
return (Bitmap) data.getExtras().get("data");
}
}
}
}
But it still get "Can't get bitmap from camera" shown. I don't known where is wrong.
I also created a working demo: https://github.com/freewind/AndroidCameraTest, you can see the full code there, and you may clone it and have a try on your own android device :)
Update
This code is working fine on android emulators, but not on my android pad.
I have seen this problem too; I removed intent.putExtra(MediaStore.EXTRA_OUTPUT,...), and it worked using the method:
stream = getContentResolver().openInputStream(data.getData());
image = BitmapFactory.decodeStream(stream);