onActivityResult doesn't behave as expected - java

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.

Related

Camera onActivityResult : resultCode is RESULT_CANCELED

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.

I am trying to select PDF file on button click but I am getting an error

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.

selecting photos from google photos crushes my app

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.

Recent captured file event interception on Android

What i wanna do is simply add log line with file name which was recently captured. Unfortunately, application fails because of below indicated error. Code and error from stack provided below.
Thanks in advance,
Anar
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=100, result=-1, data=null} to activity
{az.justx.justx/az.justx.justx.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.net.Uri android.content.Intent.getData()' on a null object
reference
private void interceptCameraButtonClick() {
Button cameraButton = (Button) findViewById(R.id.cam);
cameraButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs(); // <----
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File image = new File(imagesFolder, "AD_" + timeStamp + ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 100);
}
}
);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Test", Integer.toString(resultCode));
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Log.i("CALLED", "Image saved to:\n" +
data.getData());
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
There is no requirement that the camera send back the Uri in the Intent delivered to onActivityResult(). You already know what the Uri is, as you put it in EXTRA_OUTPUT. You just need to use that value. Be sure to include it in your saved instance state, as your process may be terminated while the camera app is in the foreground.

Change object using intent and startActivityForResult

I have an object called Contact which contains an arraylist of type Transactions.
I pass the selected contact (from a listview in activity1) to activity2 using intent and startActivityForResult.
In the second activity I create a new Transaction object and add it to the passed Contact's arraylist of transactions, return it using setResult and retrieve it using onActivityResult
My problem is that the original Contact object doesn't get the new Transaction.
Sending intent:
Intent intent = new Intent(this, AddTransactionActivity.class);
intent.putExtra("contact", selectedContact);
startActivityForResult(intent, 1);
recieving intent:
Bundle b = getIntent().getExtras();
if(b != null) {
recievedContact = (Contact)b.getParcelable("contact");
}
Sending back result:
recievedContact.addTransaction(transaction);
Intent intent = new Intent(this, Contacts_activity.class);
intent.putExtra("contact", recievedContact);
setResult(Activity.RESULT_OK, intent);
finish();
startActivity(intent);
Retrieving result:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1) {
if(resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
if(b != null) {
selectedContact = (Contact)b.getParcelable("contact");
}
} else if (resultCode == 0) {
}
}
}
edit: I put a Log.v("result test", "success"); in onActivityResult(), it doesnt show in logcat so it seems my onActivityResult method is never called.

Categories