Aim :my application take images from camera and gallery.And crop this image and save to external storage.
Issue : Application shows unfortunately photos has stooped message while clicking save button from crop page.The error happens only in marshmallow devices.working fine in all other devices.
my code to take image is given below:
final CharSequence[] options = {"Take Photo", "Choose from Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(CategoryActivity.this);
builder.setTitle("Select Pic Using...");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
try {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
pic = new File(Environment.getExternalStorageDirectory(),
"tmp_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
picUri = Uri.fromFile(pic);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, picUri);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, LOAD_IMAGE_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), LOAD_IMAGE_GALLARY);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("profile", false);
editor.commit();
// finish();
}
}
});
builder.show();
}
});
if (requestCode == LOAD_IMAGE_CAMERA && resultCode == RESULT_OK) {
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("profile", false);
editor.commit();
Intent in = new Intent(CategoryActivity.this, ImageCrop.class);
in.putExtra("URI", picUri);
in.putExtra("cat", type);
in.putExtra("contest_idadd", contestid_i);
startActivity(in);
} else if (requestCode == LOAD_IMAGE_GALLARY) {
if (data != null) {
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("profile", false);
editor.commit();
picUri = data.getData();
Intent in = new Intent(CategoryActivity.this, ImageCrop.class);
in.putExtra("URI", picUri);
in.putExtra("cat", type);
in.putExtra("contest_idadd", contestid_i);
startActivity(in);
}
}
And crop using the below code
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
picUri = (Uri) bundle.get("URI");
cat_value = (String) bundle.get("cat");
}
protected void CropImage() {
try {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(picUri, "image/*");
Log.d("piccccc",picUri+"");
intent.putExtra("crop", "true");
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 3);
intent.putExtra("aspectY", 3);
intent.putExtra("scaleUpIfNeeded", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, CROP_IMAGE);
} catch (ActivityNotFoundException e) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CROP_IMAGE) {
if (data != null) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap photo = extras.getParcelable("data");
image_array.add(photo);
crop.setImageBitmap(photo);
if (pic != null) {
if (pic.delete()) {
}
}
}
else
{
Log.d("cropppppppppppppp", requestCode + "");
}
}
In marshmallow devices images not found in saved external storage path.Anyone please give me a solution.
Add proper implementation of taking
android.permission.WRITE_EXTERNAL_STORAGE
permission in your code.
You need to handle permissions in your code from marshmallow and above:
http://developer.android.com/training/permissions/index.html
http://developer.android.com/training/permissions/requesting.html
Or build your app with SDK 22 or below, TargetSdkVersion = 22
Related
How can i upload images from camera to my web server ,
I was able to upload using image chooser like in this tuto
https://www.simplifiedcoding.net/android-upload-image-to-server/
, but i would like to choose images from camera and galery instead
public void uploadMultipart() {
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I also found this method , but it didn't work for me
How can replace the file chooser method in the above code properly to get the image path and name , and then upload it as in the tuto
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(UploadImageTest.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
For Uploading a captured image to the server the whole your code remains the same you just need to pass your captured image file path into your uploadMultipart function.
You will get captured image file path in your onActivityResult.
I'm trying to implement a function to pick a photo from android built-in gallery (not from SD card) or taking a photo using camera. After the image is picked it will be cropped by the user. An ImageView will also be updated with the cropped image. Now after picking an image from gallery, I cannot crop it -- "No Activity found to handle Intent act=com.android.camera.action.CROP" error was returned. And I also can't seem to update the ImageView with the selected image. Can someone please tell me what was wrong? Thanks.
My code is as follows:
private void ShowPickDialog() {
new AlertDialog.Builder(this)
.setTitle("Add Photo")
.setNegativeButton("Select from Photos", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),3);
}
})
.setPositiveButton("Take a Pic", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
.fromFile(new File(Environment.DIRECTORY_PICTURES,
"image.jpg")));
startActivityForResult(intent, 2);
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
startPhotoZoom(data.getData());
break;
case 2:
File temp = new File(Environment.getExternalStorageDirectory()
+ "/test.jpg");
startPhotoZoom(Uri.fromFile(temp));
break;
case 3:
if(data != null){
setPicToView(data);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, 3);
}
private void setPicToView(Intent picdata) {
Bundle extras = picdata.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
//update ImageView with selected image
mPic.setImageBitmap(photo);
}
}
Android Does Not Have a Crop Intent
you can use libraries instead
Android CropImage
I am trying to provide crop facility to image picked from gallery ,it works fine except Android 4.4.How to solve this problem? i am using following code
This is how i am calling gallery intent based on Android version
ImageView ivGallery = (ImageView) pop.findViewById(R.id.ivGallery);
ivGallery.setOnClickListener(new OnClickListener()
{
#SuppressLint("InlinedApi")
#Override
public void onClick(View v)
{
if (Build.VERSION.SDK_INT < 19)
{
Intent intent = new Intent();
pop.dismiss();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("return-data", true);
intent.putExtra("aspectX", 300);
intent.putExtra("aspectY", 300);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
startActivityForResult(intent, StaticMembers.galleryRequestCode); //1=gallery
}
else
{
picUri = ImageUtils.getTempUri();
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
pop.dismiss();
startActivityForResult(intent, StaticMembers.GALLERY_KITKAT_INTENT_CALLED);
}
}
});
This is my onActivityResult
#SuppressLint("NewApi")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == StaticMembers.galleryRequestCode && resultCode == Activity.RESULT_OK)
{
Utils.deleteTempFolder();
Bundle extras = data.getExtras();
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
bmp = extras.getParcelable("data");
thumbBitmap = Bitmap.createScaledBitmap(bmp, 100, 100, true);
imgdp.setImageBitmap(bmp);
setConfirmPicDialog();
}
else if (requestCode == StaticMembers.GALLERY_KITKAT_INTENT_CALLED && resultCode == Activity.RESULT_OK)
{
Log.d("kitkat", "Inside onActivity result for kitkat");
picUri = data.getData();
performCrop(); //what is to be done here?
}
}
private void performCrop()
{
try
{
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("return-data", true);
cropIntent.putExtra("aspectX", 300);
cropIntent.putExtra("aspectY", 300);
cropIntent.putExtra("outputX", 300);
cropIntent.putExtra("outputY", 300);
startActivityForResult(cropIntent, StaticMembers.galleryRequestCode);
}
catch (ActivityNotFoundException anfe)
{
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(UserInfoActivity.this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
What changes should be done in above code in order to have crop intent in Android 4.4
It is not a good practice to use Gallery's crop functionality. It is missing in some firmwares, so app may even crash in some cases.
Instead you can use this library android-cropimage
I have 'SherlockFragmentActivity' with overrided 'onActivityResult'.
I try to get image from camera and gallery and crop it.
The problem is I returned on my activity not fragment after onActivityResult called.
...
FragmentTransaction t = fragmentManager.beginTransaction();
LogInFragment logFrag = new LogInFragment();
t.replace(R.id.fragment_container, logFrag);
t.commit();
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
Activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:background="#color/textWhite"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>
And I also have 'SherlockFragment' where I picked image:
startImagePickerDialog(this);
public void startImagePickerDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(getSherlockActivity());
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("noFaceDetection", true);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), Const.GALLERY_PICTURE);
} catch (ActivityNotFoundException e) {
Log.e(LOG_TAG, "ActivityNotFoundException");
}
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// call android default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("noFaceDetection", true);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, Const.CAMERA_REQUEST);
} catch (ActivityNotFoundException e) {
Log.e(LOG_TAG, "ActivityNotFoundException");
}
}
});
myAlertDialog.show();
}
And 'onActivityResult' in 'SherlockFragment':
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(LOG_TAG, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != getSherlockActivity().RESULT_OK) {
Log.e(LOG_TAG, "resultCode != RESULT_OK");
return;
}
if (requestCode == Const.CAMERA_REQUEST) {
Log.d(LOG_TAG, "requestCode == CAMERA_REQUEST");
Bundle extras = data.getExtras();
if (extras != null) {
Log.d(LOG_TAG, "extras != null");
Bitmap photo = extras.getParcelable("data");
icon.setImageBitmap(photo);
}
}
if (requestCode == Const.GALLERY_PICTURE) {
Log.d(LOG_TAG, "requestCode == GALLERY_PICTURE");
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Log.d(LOG_TAG, "extras != null");
Bitmap photo = extras2.getParcelable("data");
icon.setImageBitmap(photo);
}
}
}
UPDATE
When I call camera activity my main activity call 'onSaveInstanceState' and after that 'onRestoreInstanceState'. Is it a reason?
Check your "Settings" -> "Developer options" -> "Don't keep activities" flag.
This is the nature of android if your device needs memory it destroys activities which are not visible. So you have to consider that your activity can be recreated any time. BTW "Don't keep activities" option is there to simulate your application when your device needs memory and destroys your backstack activities.
Try Like this
Change
Bitmap photo = extras.getParcelable("data");
To
Bitmap photo=(Bitmap) intent.getExtras().get("data");
Edited:-
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(LOG_TAG, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != getSherlockActivity().RESULT_OK) {
Log.e(LOG_TAG, "resultCode != RESULT_OK");
return;
}
if (requestCode == Const.CAMERA_REQUEST) {
Log.d(LOG_TAG, "requestCode == CAMERA_REQUEST");
Bitmap photo=(Bitmap) intent.getExtras().get("data");// Changed Here
icon.setImageBitmap(photo);
}
if (requestCode == Const.GALLERY_PICTURE) {
Log.d(LOG_TAG, "requestCode == GALLERY_PICTURE");
Uri imageUri= intent.getData();// Changed Here, or first decode the image to Avoid OutOfMemory Error
icon.setImageURI(imageUri);
}
}
Please replace
frag.startActivityForResult(...);
In your fragment with
startActivityForResult(...)
Now I am working on a Android application. In my app i have to submit a image from my gallery to facebook.I used the following code.
if (item == 1) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_OK) return;
Bitmap bitmap = null;
if (requestCode == PICK_FROM_FILE) {
mImageCaptureUri = data.getData();
mPath = getRealPathFromURI(mImageCaptureUri); //from Gallery
if (mPath == null){
mPath = mImageCaptureUri.getPath(); //from File Manager
}
if (mPath != null) {
System.out.println("mpath is not null"+mPath);
bitmap = BitmapFactory.decodeFile(mPath);
}
}
}
private void postToFacebook(String desc){
AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
Bundle params = new Bundle();
try {
params.putByteArray("photo",
Utility.scaleImage(getApplicationContext(),mImageCaptureUri));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
params.putString("caption", desc);
mAsyncFbRunner.request("me/photos", params, "POST",
new PhotoUploadListener());
}
Its working fine for me in emulater but in real device image is not posting.But no crash.Please help me friends
Chk your manifest first, may this will help you.
android.permission.MANAGE_ACCOUNTS