getting a permission error even after permission read_contacts is declared - java

So I initially only wanted to access contact names, and I only declared my permission in the manifest. My code was working fine then. But now I'm trying out accessing the contact number too, and that's giving me the following in logcat:
2019-11-05 18:56:02.738 30808-30919/? E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/data/phones from pid=5361, uid=10178 requires android.permission.READ_CONTACTS, or grantUriPermission()
at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:705)
at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:565)
at android.content.ContentProvider$Transport.query(ContentProvider.java:224)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
at android.os.Binder.execTransact(Binder.java:752)
2019-11-05 18:54:09.212 5113-5113/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.fresh, PID: 5113
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.contacts/contacts/lookup/2644i1d5681210d9c25a6.1450iSkype_108/738 flg=0x1 }} to activity {com.example.android.fresh/com.example.android.fresh.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/data/phones from pid=5113, uid=10178 requires android.permission.READ_CONTACTS, or grantUriPermission()
at android.app.ActivityThread.deliverResults(ActivityThread.java:4506)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4548)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/data/phones from pid=5113, uid=10178 requires android.permission.READ_CONTACTS, or grantUriPermission()
at android.os.Parcel.createException(Parcel.java:1950)
at android.os.Parcel.readException(Parcel.java:1918)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:432)
at android.content.ContentResolver.query(ContentResolver.java:847)
at android.content.ContentResolver.query(ContentResolver.java:762)
at android.content.ContentResolver.query(ContentResolver.java:720)
at com.example.android.fresh.MainActivity.getContactNumber(MainActivity.java:163)
at com.example.android.fresh.MainActivity.onActivityResult(MainActivity.java:129)
at android.app.Activity.dispatchActivityResult(Activity.java:7476)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4499)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4548) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6898) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2019-11-05 18:56:02.740 5361-5361/com.example.android.fresh E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.fresh, PID: 5361
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.contacts/contacts/lookup/2644i179d0ece8ca0b7f9.3789r1113-2916221214.1450iSkype_1113.1419r4429-2916221214.847r4510-2916221214/4513 flg=0x1 }} to activity {com.example.android.fresh/com.example.android.fresh.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/data/phones from pid=5361, uid=10178 requires android.permission.READ_CONTACTS, or grantUriPermission()
at android.app.ActivityThread.deliverResults(ActivityThread.java:4506)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4548)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/data/phones from pid=5361, uid=10178 requires android.permission.READ_CONTACTS, or grantUriPermission()
at android.os.Parcel.createException(Parcel.java:1950)
at android.os.Parcel.readException(Parcel.java:1918)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:432)
at android.content.ContentResolver.query(ContentResolver.java:847)
at android.content.ContentResolver.query(ContentResolver.java:762)
at android.content.ContentResolver.query(ContentResolver.java:720)
at com.example.android.fresh.MainActivity.getContactNumber(MainActivity.java:163)
at com.example.android.fresh.MainActivity.onActivityResult(MainActivity.java:129)
at android.app.Activity.dispatchActivityResult(Activity.java:7476)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4499)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4548) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6898) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
This is the relevant code within getContactName()
Cursor cur = getContentResolver().query(uriContact, null, null, null, null);
if (cur.moveToFirst()) {
contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));}
And the relevant code within getContactNumber()
Cursor cursorID = getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.d(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
returnval = true;
}
cursorPhone.close();
How do I fix this?

use this
public class MainActivity extends AppCompatActivity {
// Request code for READ_CONTACTS. It can be any number > 0.
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Read and show the contacts
showContacts();
}
/**
* Show the contacts in the ListView.
*/
private void showContacts() {
// Check the SDK version and whether the permission is already granted or not.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
} else {
// Android version is lesser than 6.0 or the permission is already granted.
getContactNames();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
showContacts();
} else {
Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
}
}
}
/**
* Read the name of all the contacts.
*
* #return a list of names.
*/
private void getContactNames() {
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = getContentResolver().query(uri, projection, null, null, null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
if(people.moveToFirst()) {
do {
String name = people.getString(indexName);
String number = people.getString(indexNumber);
// add number to list
// Do work...
} while (people.moveToNext());
}
people.close();
}
}

Related

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());

Unsupported Uri in ContentResolver when passing Uri returned by Intent

I have an app where the user can add music files by selecting a file or adding all the files in a selected directory into a ListView. When adding a single file, everything is fine, but for directories I'm getting Unsupported Uri. Problem is not related to permissions:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dibo.testapp, PID: 12226
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65579, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/tree/raw:/storage/emulated/0/Download/2006 A Good Year flg=0xc3 }} to activity {com.example.dibo.testapp/com.example.dibo.testapp.MainActivity}: java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2F2006%20A%20Good%20Year
at android.app.ActivityThread.deliverResults(ActivityThread.java:4360)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2F2006%20A%20Good%20Year
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:418)
at android.content.ContentResolver.query(ContentResolver.java:802)
at android.content.ContentResolver.query(ContentResolver.java:752)
at android.content.ContentResolver.query(ContentResolver.java:710)
at com.example.dibo.testapp.PlaylistFragment.addFolder(PlaylistFragment.java:380)
at com.example.dibo.testapp.PlaylistFragment.onActivityResult(PlaylistFragment.java:346)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:160)
at com.example.dibo.testapp.MainActivity.onActivityResult(MainActivity.java:152)
at android.app.Activity.dispatchActivityResult(Activity.java:7454)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4353)
This is intent request:*
private void selectDirectory() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_FOLDER);
}
Result handler:
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (requestCode == REQUEST_FILE && resultCode == Activity.RESULT_OK) {
if (resultData != null) {
addFile(resultData.getData());
}
}
if (requestCode == REQUEST_FOLDER && resultCode == Activity.RESULT_OK) {
if (resultData != null) {
addFolder(resultData.getData());
}
}
}
private void addFolder(Uri uri) {
ContentResolver contentResolver = getActivity().getContentResolver();
if (contentResolver==null) {
return;
}
Cursor cursor = contentResolver.query(
uri, // Uri
null,
null,
null,
null
);
if (cursor != null && cursor.moveToFirst()) {
int Title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
do {
String SongTitle = cursor.getString(Title);
Log.d("addFolder", SongTitle);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
}
Exception is raised in contentResolver.query. Note that everything is in Fragment Class, not in Activity.
You need first do magic thing:
Uri docUriTree = DocumentsContract.buildDocumentUriUsingTree(treeUri, DocumentsContract.getTreeDocumentId(treeUri));
Then you can read DocumentsContract.Document values from your Uri.

Application was crashed in managedQuery line in android studio

I have coded an application that contains an list that present contact information.
Application code is as follow:
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor mCursor=getContacts();
startManagingCursor(mCursor);
ListAdapter adapter=new SimpleCursorAdapter(this,
android.R.layout.two_line_list_item,
mCursor, new String[]{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME},
new int[]{android.R.id.text1, android.R.id.text2});
setListAdapter(adapter);
}
private Cursor getContacts(){
Uri uri= ContactsContract.Contacts.CONTENT_URI;
String[] projection=new String[]{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String selection=ContactsContract.Contacts.IN_VISIBLE_GROUP + "='" + ("1") + "'";
String[] selectionArgs = null;
String sortOrder=ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor out=managedQuery(uri, projection, selection, selectionArgs, sortOrder);
return out;
}
}
but application was crashed at managedQuery line.
I add also READ_CONTACTS permission to the manifest file.
What is wrong?
Edited:
Here is logcat data:
--------- beginning of crash
08-18 17:36:45.093 6464-6464/com.example.morteza.listactivitycursor E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.morteza.listactivitycursor, PID: 6464
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.morteza.listactivitycursor/com.example.morteza.listactivitycursor.MainActivity}: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{afac265 6464:com.example.morteza.listactivitycursor/u0a98} (pid=6464, uid=10098) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{afac265 6464:com.example.morteza.listactivitycursor/u0a98} (pid=6464, uid=10098) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS
at android.os.Parcel.createException(Parcel.java:1942)
at android.os.Parcel.readException(Parcel.java:1910)
at android.os.Parcel.readException(Parcel.java:1860)
at android.app.IActivityManager$Stub$Proxy.getContentProvider(IActivityManager.java:4181)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:5970)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2592)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1828)
at android.content.ContentResolver.query(ContentResolver.java:786)
at android.content.ContentResolver.query(ContentResolver.java:752)
at android.content.ContentResolver.query(ContentResolver.java:710)
at com.example.morteza.listactivitycursor.MainActivity.getContacts(MainActivity.java:35)
at com.example.morteza.listactivitycursor.MainActivity.onCreate(MainActivity.java:17)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
Caused by: android.os.RemoteException: Remote stack trace:
at com.android.server.am.ActivityManagerService.getContentProviderImpl(ActivityManagerService.java:12185)
at com.android.server.am.ActivityManagerService.getContentProvider(ActivityManagerService.java:12582)
at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:357)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3288)
at android.os.Binder.execTransact(Binder.java:731)
08-18 17:36:45.112 6464-6464/com.example.morteza.listactivitycursor I/Process: Sending signal. PID: 6464 SIG: 9
What is wrong?
You must get the user's permission. The manifest is not enough.
Check this: https://developer.android.com/training/permissions/requesting
Change to this:
private Cursor getContacts(){
Uri uri= ContactsContract.Contacts.CONTENT_URI;
String[] projection=new String[]{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String selection=ContactsContract.Contacts.IN_VISIBLE_GROUP + "= ?";
String[] selectionArgs = new String[] { "1" };
String sortOrder=ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor out=getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
return out;
}

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.

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