I am new to Java and Android but I have an app that should take a picture from the camera and save it as a file. I can start the camera and take a picture but in onActivityResult the resultCode is always RESULT_CANCELED (0). First I had an android.os.FileUriExposedException error but I followed this blog and the problem seems to be solved : https://medium.com/#ali.muzaffar/what-is-android-os-fileuriexposedexception-and-what-you-can-do-about-it-70b9eb17c6d0
Though I still have a resultCode with value 0 (RESULT_CANCEL).
Below is the code where I start the camera activity :
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
Uri uri = FileProvider.getUriForFile(
this,
this.getApplicationContext()
.getPackageName() + ".provider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, uri, FLAG_GRANT_WRITE_URI_PERMISSION | FLAG_GRANT_READ_URI_PERMISSION);
}
}
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
And below is my onActivityResult (but resultCode is always 0) :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Résultat de la capture de la photo
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Finally I followed the exact instructions given here, https://developer.android.com/training/camera/photobasics , and it now works.
Related
I would like to allow the user to pock only one image that can be referenced via a uri, I've successfully done this through the following code:
private static final int PICK_IMAGE_REQUEST = 1;
private Uri imageUri;
// Choose file extended from BottomTabView, opens all images on device
public static void openFileChooser(Context context) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity) context).startActivityForResult(intent, PICK_IMAGE_REQUEST);
// Slide Animation
((Activity) context).overridePendingTransition(R.anim.slide_in_up, R.anim.nothing);
}
// TODO: Is it better to use bitmap or URI
// Check if user has selected file and describe next step
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
// Retrieve image as a URI
imageUri = data.getData();
// Pass image URI to an intent and start activity
Intent intent = new Intent(this, UploadImageActivity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
// Slide Animation
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
this.finish();
}
}
The above code opens the following:
However, I would like to have something like the following:
Question: How can I achieve something more like the "Custom Gallery"?
if you want to custom layout pick image, you need:
create a screen and using recyclerView to make the layout as you want
get all picture gallery (https://stackoverflow.com/a/25957752/10153377)
I have an intent that picks an image (I'm calling this in a fragment):
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/png");
intent.addCategory(Intent.CATEGORY_OPENABLE);
String[] mimetypes = {"image/png","image/jpg", "image/bmp", "image/gif"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
// special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
// if you want any file type, you can skip next line
sIntent.putExtra("CONTENT_TYPE", "image/png");
sIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent chooserIntent;
if (getContext().getPackageManager().resolveActivity(sIntent, 0) != null){
// it is device with Samsung file manager
chooserIntent = Intent.createChooser(sIntent, "Open file");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
} else {
chooserIntent = Intent.createChooser(intent, "Open file");
}
try {
startActivityForResult(chooserIntent, 548);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
}
And in my activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: request code: " + requestCode);
Log.d(TAG, "onActivityResult: result: " + resultCode + " Success = " + (resultCode == RESULT_OK));
if (requestCode == 548 && resultCode == RESULT_OK) {
Uri uri = data.getData();
Log.d(TAG, "onActivityResult: URI: " + uri.toString());
Log.d(TAG, "onActivityResult: OK");
}
}
output:
onActivityResult: request code: 66084
onActivityResult: result: -1 Success = true
As you can see, the result was successful but the request code changes. so i can't check what was the request.
Your startActivityForResult() call should be on the same thing that your onActivityResult() is on.
So, if you want the onActivityResult() to be on the activity, call startActivityForResult() on the activity.
startActivityForResult() on the fragment intentionally changes the requestCode to minimize conflicts with other startActivityForResult() calls, particularly those made on other fragments in the same activity.
I am trying to select PDF file on button click but I'm getting following message on samsung device :
all apps associated with this action have been turned off blocked or
are not installed.
private void selectPDFFiles(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
return;
}
intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent,"select PDF "), 1);
}
Try below code
private void selectPDFFiles(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, 555);
}
And you can get file in activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 555:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
Update
Also try below code
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("application/pdf");
startActivityForResult(intent, 555);
I hope this can help You!
Thank You.
i'm writing an android app on java and need to let my users select and crop images from the gallery.
There is no problem when choosing an image from any native gallery, but when a user chooses to eater crop or choose an image from google photos app the app crushes.
I cannot figure out what is the source of the problem so any answer will be helpful
this is the code i'm using
class fields:
private Uri imageUri;
opening the camera:
private void camOpen() {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "file" + String.valueOf(System.currentTimeMillis()) + ".png");
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
imageUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
i.putExtra("return-data", true);
startActivityForResult(i, CAMERA_CODE);
}
opening the gallery:
private void galleryOpen() {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(i, "select file"), SELECT_PHOTO_CODE);
}
cropping the image:
private void cropImage() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(imageUri, "image/*");
cropIntent.putExtra("crop", true);
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_CODE);
} catch (Exception e) {}
}
the result handler:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CODE && resultCode == Activity.RESULT_OK) {
cropImage();
} else if (requestCode == SELECT_PHOTO_CODE && resultCode == Activity.RESULT_OK) {
if (data != null) {
imageUri = data.getData();
cropImage();
}
} else if (requestCode == CROP_CODE && resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
Bitmap b = bundle.getParcelable("data");
hasImageChanged=true;
ivProfilePic.setImageBitmap(b);
capturedImage = b;
}
}
thank you for any useful help...
Android does not support crop intent because croping is not part of android api.
So i recommend you for Using library
the issue was with the crop intent. I ended up using the uCrop library and it fixed the problem.
I am Trying To upload image to server from gallery and camera.When i Choose image from gallery to upload to server its Work Perfactly.But when i Select camera captured Image for upload to server Its Crash And Showing the error.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
At OnActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && 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();
decodeFile(picturePath);
new ImageUploadTask().execute();
}else {
Toast.makeText(getApplicationContext(), "User Canceled",
Toast.LENGTH_LONG).show();
}
}
i got the error on this line in onActivityResult
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
The method i used for open camera on button click.
loadimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(Add_Info.this);
builder.setMessage("Select Image From")
.setCancelable(true)
.setPositiveButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg"));
}
})
.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Help Me solve this problem.I don't know How t get this error even after i used is already in my Previous PROJECT.
THANKS in Advance
I had same issue when working with Camera api and Intent of onActivityResult, finally I found out it depends on your android device version, in Android M (Marshmallow - 6.0–6.0.1 ) onActivityResult intent is like below :
requestCode : 230 resultCode : -1 intent :Intent{dat=file:///storage/emulated/0/Pictures/Rahnama/IMG_20160508_121332_1519065 564.jpg typ=image/jpeg } RESULT_OK : -1
and for android versions lower than Marshmallow:
requestCode : 230 resultCode : -1 intent : Intent { dat=content://media/external/images/media/309 (has extras) } RESULT_OK : -1
I think you must check android version onActivityResult and the for android versions Marshmallow to get direct file from path in the Uri and Intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M){
final Uri data = intent.getData();
final File file = new File(data.getPath());
// now you can upload your image file
}else{
// in android version lower than M your method must work
}
I hope it can be useful for you.
if (null != account.getPhotoUrl()) {
// Write code here
}
I meet this problem either, after many test, I found its because I set the attribute named android:windowIsTranslucent=true, if I delete this attribute from style, it always work.