Android: Gallery picker and Camera intent crashes upon onActivityresult - java

So I have this page in my app which lets user choose to either take a picture with their camera or pick an image from gallery.
Upon choosing an alert dialog with the chosen image set as icon will be shown confirming.
Now here comes my problem, whenever I try to get an image, using either the gallery picker or camera intent, my app crashes right after with error:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {my.com.thelorry.ken.thelorrypartner/com.example.Activity}:
If I am using the camera intent or if I used the gallery picker this shows:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example/com.example.Activity}:
Below are the codes I used to start my camera intent:
public void startCamera(){
ContentValues values;
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From phone Camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
And my codes to start gallery picker:
public void pickGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
}
This is my codes to handle the results:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
photo = null;
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK ) {
try {
photo = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
photo = getResizedBitmap(photo, 600, 450);
File file = new File(imageurl);
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
createDialog(photo);
}if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null) {
Uri pickedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
photo = getResizedBitmap(bitmap, 600, 450);
cursor.close();
createDialog(photo);
}
}
Also, odd enough, this codes seems to crash only on Samsung phones based on my crash reports, and only on some models such as the Galaxy J7, Note5, Note4 (so far, app doesn't have a huge userbase yet).
Edit: After actually getting a phone that could reproduce the crash I realize that codes above might not be the problem after all, this is the what I have in logcats:
Process: com.example, PID: 6220
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example/com.example.Activity}: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.app.ActivityThread.deliverResults(ActivityThread.java:4019)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.content.res.Resources.getValue(Resources.java:1542)
at android.support.v7.widget.ResourcesWrapper.getValue(ResourcesWrapper.java:204)
at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:321)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:197)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:192)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:66)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:71)
at com.android.internal.app.AlertController.setupTitle(AlertController.java:565)
at com.android.internal.app.AlertController.setupView(AlertController.java:474)
at com.android.internal.app.AlertController.installContent(AlertController.java:240)
at android.app.AlertDialog.onCreate(AlertDialog.java:356)
at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
at android.app.Dialog.show(Dialog.java:274)
at com.example.Activity.createDialog(Activity.java:697)
at com.example.Activity.onActivityResult(Activity.java:618)
at android.app.Activity.dispatchActivityResult(Activity.java:6441)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062) 
at android.app.ActivityThread.access$1400(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5930) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 
Also:
FATAL EXCEPTION: main
Process: com.example, PID: 9794
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1889, result=-1, data=Intent { dat=content://media/external/images/media/3196 flg=0x1 (has extras) }} to activity {com.example/com.example.Activity}: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.app.ActivityThread.deliverResults(ActivityThread.java:4019)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.content.res.Resources.getValue(Resources.java:1542)
at android.support.v7.widget.ResourcesWrapper.getValue(ResourcesWrapper.java:204)
at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:321)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:197)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:192)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:66)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:71)
at com.android.internal.app.AlertController.setupTitle(AlertController.java:565)
at com.android.internal.app.AlertController.setupView(AlertController.java:474)
at com.android.internal.app.AlertController.installContent(AlertController.java:240)
at android.app.AlertDialog.onCreate(AlertDialog.java:356)
at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
at android.app.Dialog.show(Dialog.java:274)
at com.example.Activity.createDialog(Activity.java:697)
at com.example.Activity.onActivityResult(Activity.java:639)
at android.app.Activity.dispatchActivityResult(Activity.java:6441)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062) 
at android.app.ActivityThread.access$1400(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5930) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 
More info, this is my createDialog function which actually causing problems.
Drawable icon = new BitmapDrawable(this.getResources(),photo);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.business_post_camera_dialog_title))
.setMessage(getString(R.string.business_post_camera_dialog_message))
.setCancelable(false)
.setPositiveButton(R.string.sign_confirm_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
doSomething();
}
})
.setNegativeButton(R.string.sign_cancel_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(-1).setIcon(icon); //setIcon(-1) as a workaround for bug in Android Lollipop 5.0
AlertDialog alert = builder.create();
alert.show();
Apparently .setIcon(-1) causes the crash on Samsung phones, but without it I wouldn't be able to display my images there on certain phones still on Lollipop 5.0, any solution?

The problem is here:
...
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
...
You are trying to use setImageResource(int id) with a non-exist image. You can use it like this:
imageView.setImageResource(R.drawable.image_name)
The same thing is available for TextView too.
textView.setText("" + intValue);

Try to use below method for dialog,
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Drawable icon = new BitmapDrawable(this.getResources(),photo);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.business_post_camera_dialog_title))
.setMessage(getString(R.string.business_post_camera_dialog_message))
.setCancelable(false)
.setPositiveButton(R.string.sign_confirm_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
doSomething();
}
})
.setNegativeButton(R.string.sign_cancel_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
builder.setIcon(-1).setIcon(icon);
} else{
builder.setIcon(icon);
}
AlertDialog alert = builder.create();
alert.show();

Related

How to show Alert Dialog box in Service android

Iam new to android,I want to show alert dialog box in service,I used two methods as shown below
First one without Layout
AlertDialog.Builder builder = new AlertDialog.Builder(MyService.this);
builder.setTitle("Test dialog");
builder.setMessage("Content");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
AlertDialog alert = builder.create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
alert.show();
but iam getting error like this as shown as below
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.materialdialoginservice, PID: 25846
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:993)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:387)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
at android.app.Dialog.show(Dialog.java:344)
at com.example.materialdialoginservice.MyService$3.run(MyService.java:98)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7561)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
Second one with Layout
AlertDialog.Builder builder = new AlertDialog.Builder(MyService.this);
View view = View.inflate(context, R.layout.activity_layout_view, null);
AlertDialog dialog = builder.create();
dialog.setView(view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0 new features
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY - 1);
} else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
dialog.show();
Window dialogWindow = dialog.getWindow();
dialogWindow.setGravity(Gravity.CENTER);
I am getting error like this,
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.textstuff, PID: 27418
java.lang.RuntimeException: Unable to start service com.example.textstuff.MyService#134fed7 with Intent { cmp=com.example.textstuff/.MyService }: android.view.WindowManager$InvalidDisplayException: Unable to add window android.view.ViewRootImpl$W#124c071 -- the specified display can not be found
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4196)
at android.app.ActivityThread.access$2000(ActivityThread.java:233)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1946)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7561)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
Added permission in Manifest file like this
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW"/>
Just remove :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 8.0 new features
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY - 1);
} else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
And try :
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
UPDATE
In Android 6.0 Marshmallow, the user must explicitly allow your app to "draw over other apps". So add
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Now in marshmallow use this method to handle runtime permission:
#TargetApi(Build.VERSION_CODES.M)
private void handleOverlaySettings() {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
try {
startActivityForResult(intent, 11);
} catch (ActivityNotFoundException e) {
Log.e(TAG, e.getMessage());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 11:
final boolean overlayEnabled = Settings.canDrawOverlays(this);
// handle the remaining logic
break;
}
}
Now show the dialog in service as below:
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this, R.style.AppTheme_MaterialDialogTheme);
dialogBuilder.setTitle(R.string.dialog_title);
dialogBuilder.setMessage(R.string.dialog_message);
dialogBuilder.setNegativeButton(R.string.btn_back,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
final AlertDialog dialog = dialogBuilder.create();
final Window dialogWindow = dialog.getWindow();
final WindowManager.LayoutParams dialogWindowAttributes = dialogWindow.getAttributes();
// Set fixed width (350dp) and WRAP_CONTENT height
final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialogWindowAttributes);
lp.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 350, getResources().getDisplayMetrics());
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialogWindow.setAttributes(lp);
// Set to TYPE_SYSTEM_ALERT so that the Service can display it
dialogWindow.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialogWindowAttributes.windowAnimations = R.style.DialogAnimation;
dialog.show();
All set now this solution should work. Good luck

Get Real Path of mp3 file from Uri

I have picked audio file from Content Picker intent inside Fragment which extend PreferenceFragmentCompat
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("audio/mpeg");
startActivityForResult(intent, 1);
and Retrieved Uri from onActivityResult
#Override
public void onActivityResult(int requestCode, int resultcode, Intent data) {
if (requestCode == 1 && resultcode == Activity.RESULT_OK) {
audio = data.getData();
inputfile= (FileInputStream getActivity().getApplicationContext().getContentResolver().openInputStream(data.getData());
}
super.onActivityResult(requestCode, resultcode, data);
}
Where audio is declared public(Uri audio).
Now i wanted this audio file to be copied to a Directory in App Directory(/data/data/com.example.focusit).For this i need to get Real path of audio file from URI
public String getRealPathFromUri(Uri contentUri) {
String res = null;
String[] proj = {
MediaStore.Audio.Media.DATA
};
Cursor cursor = (Cursor) getActivity().getApplicationContext().getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Now to copy audio file to my directoy i used this code
File audiofile = new File(audio.getPath());
String realpath = getRealPathFromUri(audio);
File file = new File("/data/data/com.example.focusit/Focusit_SOS/tt_temp.mp3");
if (!file.exists()) {
Toast.makeText(getContext(), "Director focus it does not existed", Toast.LENGTH_SHORT).show();
file.mkdirs();
}
try {
FileUtils.copy(new FileInputStream(audiofile), new FileOutputStream(file));enter code here
} catch (IOException e) {
e.printStackTrace();
But problem is that in function getRealPathFromUri(Uri ContentUri) cursor.movetoFirst() is returning false.Any idea how to deal with it.
Output of audio.getpath() is /external/audio/media/8099.
i tried one solution by creating Input stream directly from Uri in onActivityResult()
inputfile= (FileInputStream) getActivity().getApplicationContext().getContentResolver().openInputStream(data.getData());
but i am getting exception
2020-10-28 07:41:31.333 21292-21292/com.example.focusit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.focusit, PID: 21292
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://media/external/audio/media/8099 (has extras) }} to activity {com.example.focusit/com.example.focusit.SettingsActivity}: java.lang.SecurityException: com.example.focusit has no access to content://media/external/audio/media/8099
at android.app.ActivityThread.deliverResults(ActivityThread.java:4905)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4946)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.SecurityException: com.example.focusit has no access to content://media/external/audio/media/8099
at android.os.Parcel.createException(Parcel.java:2074)
at android.os.Parcel.readException(Parcel.java:2042)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:151)
at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:705)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1702)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1518)
at android.content.ContentResolver.openInputStream(ContentResolver.java:1202)
at com.example.focusit.SettingsActivity$SettingsFragment.onActivityResult(SettingsActivity.java:227)
at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:170)
at android.app.Activity.dispatchActivityResult(Activity.java:8249)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4898)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4946) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:224) 
at android.app.ActivityThread.main(ActivityThread.java:7520) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) `
Providing Storage access will resolve Exception
java.lang.SecurityException: com.example.focusit has no access to content:
Do not open a FileInputStream on a path you do not have.
Instead open an InputStream on the obtained uri directly.
InputStream is = getContentResolver().openInputStream(data.getData());

MediaStore.Images.Media.insertImage returns null in some devices

Possibly Duplicate but did not find any solution.
I am trying to modify image and saving it to device using MediaStore. with following code -:
public class Utils {
private Utils() {
}
static Uri getUri(Context context, Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, "Title", null); //returning null in some devices
Log.d("TAG", "getUri: "+path);
return Uri.parse(path); //this is returning null which cause the app crash
}
static Bitmap getBitmap(Context context, Uri uri) throws IOException {
return MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
}
}
This code is working well in most of devices but the problem is that MediaStore.Images.Media.insertImage returning null in some devices like -:
1. Samsung J7(2016)
2. LG Magna LTE
3. Android Emulator API 21
I am surprised this app is working in Android Emulator API 26 . but getting crashed on Android Emulator API 21
I have searched google and I have also find the same question here but not find any sufficient answer.
NOTE - : I have used Runtime Permission for Read/Write External Storage
But still getting crash in mentioned devices. Below is my crash log-:
Fatal Exception: java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=1, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:51 flg=0x1 }} to activity {com.example/com.scanlibrary.ScanActivity}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:470)
at android.net.Uri$StringUri.<init>(Uri.java:460)
at android.net.Uri.parse(Uri.java:432)
at com.scanlibrary.Utils.getUri(Utils.java:24)
at com.scanlibrary.PickImageFragment.postImagePick(PickImageFragment.java:228)
at com.scanlibrary.PickImageFragment.onActivityResult(PickImageFragment.java:208)
at android.app.Activity.dispatchActivityResult(Activity.java:6196)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Thanks
Instead of using below code-:
String path = MediaStore.Media.insertImage(context.getContentResolver(),bitmap,"Title",null);
Use this code(below)-:
ContentValues values=new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"Title");
values.put(MediaStore.Images.Media.DESCRIPTION,"From Camera");
Uri path=getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
pass values as null if it is not working.
protected void onActivityResult(int requestCode, int resultCode,Intent data) {
if (requestCode == RequestPermissionCode && resultCode == RESULT_OK) {
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePathColumn, null, null, null);
if (cursor == null)
return;
// find the file in the media area
cursor.moveToLast();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = "file:///"+cursor.getString(columnIndex);
cursor.close();
actualImage = FileUtil.from(this,Uri.parse(filePath));
actualImageView.setImageBitmap(BitmapFactory.decodeFile(actualImage.getAbsolutePath()));
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Use onActvittyResult method i hope it will work.

java.lang.RuntimeException: Unable to resume activity Attempted to access a cursor after it has been closed

I have following method to pass selected image path to another activity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Log.d("fsd", "onActivityResult: ");
Intent intent = new Intent(getApplicationContext(), AddContentImage.class);
Bundle b = new Bundle();
b.putString("path", selectedImagePath);
intent.putExtras(b);
startActivity(intent);
}
}
}
Which is actually working fine, but I gets following error, when back button is pressed.
java.lang.RuntimeException: Unable to resume activity : android.database.StaleDataException: Attempted to access a cursor after it has been closed.
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3169)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3247)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5582)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
at android.database.BulkCursorToCursorAdaptor.throwIfCursorIsClosed(BulkCursorToCursorAdaptor.java:63)
at android.database.BulkCursorToCursorAdaptor.requery(BulkCursorToCursorAdaptor.java:132)
at android.database.CursorWrapper.requery(CursorWrapper.java:228)
at android.app.Activity.performRestart(Activity.java:6363)
at android.app.Activity.performResume(Activity.java:6389)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3158)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3247)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5582)
This error only occurs if second activity is opened from onActivityResult.
Edited:
getpath method
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
// this is our fallback here
return uri.getPath();
}
How can I solve this error?
First, managedQuery() has been deprecated for over six years. Do not use it. Use a CursorLoader, or use ContentResolver and query() on some form of background thread.
Second, be sure to follow the instructions of the things that you use. In this case, you missed the instructions for using managedQuery():
Warning: Do not call close() on a cursor obtained using this method, because the activity will do that for you at the appropriate time.
Beyond that, a Uri does not point to a file in most cases, and so you cannot get a "real path" to that file.

Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { }} to activity

I have a method that gives users the option to use the camera intent to capture a photo to then upload to the application:
public void UploadImageToFeed() {
CharSequence colors[] = new CharSequence[] {"Gallery", "Take a Picture"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Upload an Image");
builder.setIcon(R.drawable.ic_upload_image);
builder.setItems(colors, (dialog, which) -> {
if (which == 0) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
} else {
Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), "camera.jpg");
Uri uri = Uri.fromFile(file);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(captureIntent, SELECT_PHOTO);
}
});
builder.show();
}
When a camera image is taken, I process the image to reduce its size before it is actually uploaded. This is where I get a crash.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
ImageView imageToUpload = (ImageView) findViewById(R.id.imageToUpload);
imageToUpload.setVisibility(View.VISIBLE);
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
int nh = (int) (yourSelectedImage.getHeight() * (512.0 / yourSelectedImage.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(yourSelectedImage, 512, nh, true);
imageToUpload.setImageBitmap(scaled);
}
}
}
Exception:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/197149/ORIGINAL/NONE/724456777 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F197149/ORIGINAL/NONE/724456777} }} to activity {com.yitter.android/com.yitter.android.activity.YeetActivity}: java.lang.IllegalArgumentException: width and height must be > 0
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:829)
at android.graphics.Bitmap.createBitmap(Bitmap.java:808)
at android.graphics.Bitmap.createBitmap(Bitmap.java:739)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:615)
at com.yitter.android.activity.YeetActivity$override.onActivityResult(YeetActivity.java:350)
at com.yitter.android.activity.YeetActivity$override.access$dispatch(YeetActivity.java)
at com.yitter.android.activity.YeetActivity.onActivityResult(YeetActivity.java:0)
at android.app.Activity.dispatchActivityResult(Activity.java:6456)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) 
at android.app.ActivityThread.-wrap16(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 
My first suspicion was that the error occurs where I'm scaling the camera image down, but it's not so obvious from my stack trace. When I remove the two lines of code responsible for rescaling the image, I get the following error:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { }} to activity {com.yitter.android/com.yitter.android.activity.YeetActivity}: java.lang.NullPointerException: uri
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: uri
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
at com.yitter.android.activity.YeetActivity.onActivityResult(YeetActivity.java:366)
at android.app.Activity.dispatchActivityResult(Activity.java:6456)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) 
at android.app.ActivityThread.-wrap16(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
What could be going wrong?
ACTION_IMAGE_CAPTURE does not return a Uri. You know the Uri where the image is supposed to be — you put it in EXTRA_OUTPUT. You need to hold onto that location (including via the saved instance state Bundle) and look there.
Also note that Uri.fromFile() will not work on Android 7.0+, once you raise your targetSdkVersion to 25 or higher.
This sample app demonstrates using ACTION_IMAGE_CAPTURE, including using FileProvider to avoid Uri.fromFile().

Categories