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
Related
So am actually implementing a feature where user selects image from gallery and then in this activity if the user clicks on crop button a layout from this library becomes visible https://github.com/ArthurHub/Android-Image-Cropper then the user can crop and then click another button to save it.
But the problem is after cropping the image when clicked on cropclose it the layout goes away and imageview shows the cropped image but it just shows a blank image.
Edit- I found the problem thanks to #Usama Altaf
So I added a Log logging the image uri and it said this
24333-24333/com.margsapp.messenger D/imageUri: null
So the problem is imageuri is null How to fix this?
public class SendImageActivity extends AppCompatActivity implements CropImageView.OnSetImageUriCompleteListener,
CropImageView.OnCropImageCompleteListener {
ImageView imageView;
ImageView cancel, cropopen,cropclose, edit_open,edit_close;
EditText text;
ImageButton btn_send;
CropImageView cropImageView;
PhotoEditorView photoEditorView;
Uri imageUri;
Intent intent;
RelativeLayout messagebox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_image);
intent = getIntent();
imageUri = Uri.parse(intent.getStringExtra("imageUri"));
btn_send = findViewById(R.id.btn_send);
imageView = findViewById(R.id.imageview);
imageView.setImageURI(imageUri);
cropopen = findViewById(R.id.cropopen);
cropclose = findViewById(R.id.cropclose);
cropImageView = findViewById(R.id.cropImageView);
cropopen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cropImageView.setImageUriAsync(imageUri);
cropImage();
}
});
cropclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageView.setVisibility(View.GONE);
cropImage();
cropImageView.getCroppedImageAsync();
}
});
}
private void cropImage() {
cropImageView.setOnSetImageUriCompleteListener(this);
cropImageView.setOnCropImageCompleteListener(this);
}
#Override
public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) {
if (error == null) {
Toast.makeText(getApplicationContext(), "Image load successful", Toast.LENGTH_SHORT).show();
} else {
Log.e("AIC", "Failed to load image by URI", error);
Toast.makeText(getApplicationContext(), "Image load failed: " + error.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
#Override
public void onCropImageComplete(CropImageView view, CropImageView.CropResult result) {
handleCropResult(result);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
handleCropResult(result);
}
}
private void handleCropResult(CropImageView.CropResult result) {
if(result.getError() == null){
Toast.makeText(getApplicationContext(), "Image crop Success: ", Toast.LENGTH_LONG).show();
imageUri = result.getUri();
imageView.setImageURI(imageUri);
cropImageView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
}
else {
Log.e("AIC", "Failed to crop image", result.getError());
Toast.makeText(
getApplicationContext(),
"Image crop failed: " + result.getError().getMessage(),
Toast.LENGTH_LONG)
.show();
}
}
}
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.
hello i am struck in this coding first of all i am having two image view's when we click one of them the chooser dialog box will open which is having two option 1.take photo 2.select from gallery when i select from galley everything is working fine where as the problem is,
when we select take photo option and after we had captured the image when setting its preview for the first image its working fine where as the problem here is in the second image. when we select take photo option and after capturing the photo it is replacing the image of the first image with the second image.
This is Java Code:
public class PrescriptionUpload extends ActionBarActivity {
ImageView uploadimage1, uploadimage2;
Bitmap imagemap, imagemapsec;
int imageupload = 1;
int imagesecpload = 2;
int requestcamera = 0;
Button uploadpric;
StringBuilder sb;
String uploadimg2;
Toolbar include2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prescriptionimages);
include2= (Toolbar) findViewById(R.id.include2);
setSupportActionBar(include2);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
uploadimage1 = (ImageView) findViewById(R.id.uploadimage1);
uploadimage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectimage(imageupload);
}
});
uploadimage2 = (ImageView) findViewById(R.id.uploadimage2);
uploadimage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectimage(imagesecpload);
}
});
}
private void selectimage(final int number) {
final CharSequence[] items = {"Take Photo", "Choose from Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(PrescriptionUpload.this);
builder.setTitle("Add Prescription");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, requestcamera);
} else if (items[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
number);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == imageupload) {
try {
imagemap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
uploadimage1.setImageBitmap(imagemap);
uploadimage2.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == imagesecpload) {
try {
imagemapsec = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
uploadimage2.setImageBitmap(imagemapsec);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == requestcamera) {
if (uploadimage1.getId()==R.id.uploadimage1){
Bitmap testurl = (Bitmap) data.getExtras().get("data");
uploadimage1.setImageBitmap(testurl);
uploadimage2.setVisibility(View.VISIBLE);
}else if (uploadimage2.getId()==R.id.uploadimage2){
Bitmap testurltwo = (Bitmap) data.getExtras().get("data");
uploadimage2.setImageBitmap(testurltwo);
}
}
}
}
i had solved my problem using onActivityResult and with the increment of the variable
The complete code of my Fragment:
public class ProfileEditPictureFragment extends BaseFragment implements OnClickListener {
private ImageView imageView = null;
private Button buttonPick = null;
private Button buttonSave = null;
private Button buttonCancel = null;
private File tempFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
this.tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
}
else {
this.tempFile = new File(this.getActivity().getFilesDir(), "temp_photo.jpg");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_picture_edit, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.imageView = (ImageView) view.findViewById(R.id.profile_picture_edit_imageview_photo);
this.buttonPick = (Button) view.findViewById(R.id.profile_picture_edit_button_pick);
this.buttonPick.setOnClickListener(this);
this.buttonSave = (Button) view.findViewById(R.id.profile_picture_edit_button_save);
this.buttonSave.setOnClickListener(this);
this.buttonCancel = (Button) view.findViewById(R.id.profile_picture_edit_button_cancel);
this.buttonCancel.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("ProfileEditPicture", "requestCode: " + requestCode);
Log.v("ProfileEditPicture", "resultCode: " + resultCode);
Log.v("ProfileEditPicture", "data: " + data);
Bitmap bitmap = null;
if(resultCode == Activity.RESULT_OK) {
if (requestCode == Globals.REQUEST_PICK_PHOTO) {
try {
InputStream inputStream = this.getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(this.tempFile);
Helper.copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
this.startCropImage();
} catch (Exception e) {}
} else if (requestCode == Globals.REQUEST_CROP_PHOTO) {
String path = data.getStringExtra(CropActivity.IMAGE_PATH);
if (path == null) {
return;
}
bitmap = BitmapFactory.decodeFile(this.tempFile.getPath());
this.imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.profile_picture_edit_button_pick : {
this.pickPicture();
} break;
case R.id.profile_picture_edit_button_save : {
} break;
case R.id.profile_picture_edit_button_cancel : {
this.getActivity().finish();
}
}
}
private void pickPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "Select Picture"), Globals.REQUEST_PICK_PHOTO);
}
private void startCropImage() {
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(CropActivity.IMAGE_PATH, this.tempFile.getPath());
intent.putExtra(CropActivity.SCALE, true);
intent.putExtra(CropActivity.ASPECT_X, 3);
intent.putExtra(CropActivity.ASPECT_Y, 2);
this.startActivityForResult(intent, Globals.REQUEST_CROP_PHOTO);
}
}
But the resultCode is always 0 and the data is always null. Permissions are set ofcourse.
So how can i pick images from the gallery?
I test it on Nexus 4 with Android 5.0.1
Try ACTION_PICK like this
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
And on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && 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]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
I was having same problem in one of my activities when I set launchMode="singleInstance" in manifest for that activity. It works fine when I remove that attribute. Although I don't know reason for this behaviour.
If I have multiple buttons on a view to call camera intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE) and a ImageView for the preview of each image and I need to know which button called it in onActivityResult so I know which corresponding preview to use how do I pass an identifying variable? Below is current code that only works with one image.
Picture button:
final ImageButton cameraTakePhotoButton = (ImageButton) photoPromptOption.findViewById(R.id.cameraTakePhotoButton);
cameraTakePhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
final ImageView questionPhotoResult = (ImageView) findViewById(R.id.questionPhotoResult);
questionPhotoResult.setImageBitmap(thumbnail);
}
}
}
Ended up using a ListView and custom adapter then having it iterate over an ArrayList with objects of class Photo... I update the Bitmap (thumbnail) property for the Photo objects when I take the picture then refresh the ListView. This method works very well.
photoListView.setAdapter(new ArrayAdapter<Photo>(this, R.layout.photo_list_item, photosList) {
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row = null;
final Photo thisPhoto = getItem(position);
if (null == convertView) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.photo_list_item, null);
} else {
row = convertView;
}
photoPreview.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
File photoDirectory = new File(Environment.getExternalStorageDirectory()+"/Pictures/appName");
if(!photoDirectory.isDirectory()) {
photoDirectory.mkdir();
}
File photo = new File(Environment.getExternalStorageDirectory()+"/Pictures/appName/", thisPhoto.getId()+"_photo.jpg");
CameraHandlerSingleton.setPictureUri(Uri.fromFile(photo));
CameraHandlerSingleton.setPhotoId(thisPhoto.getId());
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
return row;
}
});
Then my onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
if(requestCode == CAMERA_PIC_REQUEST) {
Uri selectedImage = CameraHandlerSingleton.getPictureUri();
String photoId = CameraHandlerSingleton.getPhotoId();
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap thumbnail;
try {
thumbnail = Bitmap.createScaledBitmap(android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage), 300, 200, true);
p.setThumbnail(thumbnail);
p.setTaken(true);
} catch(FileNotFoundException e) {
Toast.makeText(this, "Picture not found.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch(IOException e) {
Toast.makeText(this, "Failed to load.", Toast.LENGTH_SHORT).show();
Log.e("Camera", e.toString());
} catch(Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
Log.e("Camera Exception", e.toString());
e.printStackTrace();
}
startActivity(getIntent());
finish();
}
}
}
Yikes. Why not use requestCode? Just tag each view with a unique code, making sure it doesn't clash with any other intents you're throwing around. Alternatively, you can use Object.hashCode() , but again, watch out for clashes.
cameraTakePhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST + v.getTag());
}
});
Then check it in your handler:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CAMERA_PIC_REQUEST + button1.getTag()) {
// do stuff
}
else if (requestCode == CAMERA_PIC_REQUEST + button2.getTag()) {
// do more stuff
}
}
}
If you have many buttons (or items in a ListView) that you're going to handle similarly, you can use a Map to recover the calling view from the tag.