Created
May 7, 2025 20:13
-
-
Save unlocomqx/ce5fba6bc5a1bd6a23ae2a6bd86dce0c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (result.resultCode == Activity.RESULT_OK && result.data != null) { | |
val uriList = mutableListOf<Uri>() | |
if (result.data?.clipData != null) { | |
for (i in 0 until result.data?.clipData?.itemCount!!) { | |
uriList.add(result.data?.clipData?.getItemAt(i)?.uri!!) | |
} | |
} else { | |
uriList.add(result.data?.data!!) | |
} | |
Log.i("ContactsManager", "contactUri: $uriList") | |
if (uriList.isEmpty()) { | |
val ret = JSObject() | |
ret.put("error", "No contacts were picked") | |
ret.put("data", "") | |
invoke.resolve(ret) | |
return | |
} | |
val queryFields = arrayOf( | |
ContactsContract.Contacts._ID, | |
ContactsContract.Contacts.DISPLAY_NAME, | |
ContactsContract.Contacts.HAS_PHONE_NUMBER | |
) | |
val selection = String.format("%s > 0", ContactsContract.Contacts.HAS_PHONE_NUMBER) | |
val contacts: MutableList<JSObject> = ArrayList() | |
for (uri in uriList) { | |
val cursor = activity.contentResolver | |
.query(uri, queryFields, selection, null, null) | |
try { | |
if (cursor == null) { | |
val ret = JSObject() | |
ret.put("error", "No contacts were picked") | |
ret.put("data", "") | |
invoke.resolve(ret) | |
return | |
} | |
Log.i("ContactsManager", "contacts: $contacts") | |
while (cursor.moveToNext()) { | |
val idIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID) | |
val contactId = cursor.getString(idIndex) | |
val phoneCursor: Cursor = activity.managedQuery( | |
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, | |
null, | |
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, | |
null, | |
null | |
) | |
while (phoneCursor.moveToNext()) { | |
val phone = phoneCursor.getString( | |
phoneCursor | |
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER) | |
) | |
Log.i("ContactsManager", "phone: $phone") | |
val contact = JSObject() | |
contact.put("name", cursor.getString(1)) | |
contact.put("tel", phone) | |
contacts.add(contact) | |
} | |
Log.i("ContactsManager", "name: $contactId") | |
} | |
} catch (e: Exception) { | |
Log.e("ContactsManager", "Error: ${e.message}", e) | |
val ret = JSObject() | |
ret.put("error", "An error occurred while fetching contacts: ${e.message}") | |
ret.put("data", "") | |
invoke.resolve(ret) | |
return | |
} finally { | |
cursor!!.close() | |
} | |
} | |
val ret = JSObject() | |
ret.put("error", "") | |
ret.put("data", contacts) | |
invoke.resolve(ret) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment