My app "calls" the device's app that allows user to insert a new contact. After a contact is saved on the device, I want to "query" the Uri of that contact.
My code works on emulators (Android 4, 5, 6, 7) but not on my Huawei P8, and I cant' understand why.
First, I request permission both in the Activity and in Manifest.xml
:
ActivityCompat.requestPermissions(this, new String [] {Manifest.permission.WRITE_CONTACTS,
Manifest.permission.READ_CONTACTS},
101);
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
This is the code of my app
1) I "call" the device's app that manages the Contacts
Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
intent.putExtra("finishActivityOnSaveCompleted", true);
startActivityForResult(intent, ADD_FRIEND_CODE);
2) after saving a new contact, my app comes back to foreground and the onActivityResult()
method is called:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case ADD_FRIEND_CODE:
if(resultCode == RESULT_OK){
/*I get the URI of the contact. This works both
on emulator and real device*/
Uri lastContactUri = data.getData();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(lastContactUri, null, null, null, null);
/*On emulator the cursor is full, on real device is empty*/
if (cursor.moveToFirst()) {
cursor.moveToPrevious();
while (cursor.moveToNext()) {
String name = "";
if (cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME) > -1) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
Toast.makeText(this, name , Toast.LENGTH_SHORT).show();
}
}
cursor.close();
break;
}
}
Does anybody understand why my code works on many emulators and not on my real devices.