Skip to content

Instantly share code, notes, and snippets.

@NizarETH
Created November 21, 2022 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NizarETH/13f23518b1849b9c0a1f322896c0e90c to your computer and use it in GitHub Desktop.
Save NizarETH/13f23518b1849b9c0a1f322896c0e90c to your computer and use it in GitHub Desktop.
1- Class contact avec constructeur principal
2- gradle
3- manifest
4- function contacts
Ps: check
========================================================================
class Contact
========================================================================
class Contact(var number: String, var name: String)
========================================================================
build gradle
========================================================================
implementation 'com.karumi:dexter:6.2.3'
========================================================================
permissions in Manifest
========================================================================
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
========================================================================
function in MainActivity
========================================================================
fun getContactListFromLocal() {
val myContacts: MutableList<Contact?> =
ArrayList<Contact?>()
// Get query phone contacts cursor object.
val readContactsUri =
ContactsContract.CommonDataKinds.Phone.CONTENT_URI
val cursor: Cursor =
this@MainActivity.getContentResolver()
.query(readContactsUri, null, null, null, null)!!
if (cursor != null) {
cursor.moveToFirst()
// Loop in the phone contacts cursor to add each contacts in phoneContactsList.
do {
// Get contact display name.
val displayNameIndex =
cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
if (displayNameIndex != -1) {
val userDisplayName = cursor.getString(displayNameIndex)
// Get contact phone number.
val phoneNumberIndex =
cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
var phoneNumber = cursor.getString(phoneNumberIndex)
phoneNumber = phoneNumber!!.replace("-", "")
phoneNumber = phoneNumber.replace(" ", "")
val regex: String = "^[+]?[(]?[0-9]{3}[)]?[-\\\\.]?[0-9]{3}[-\\\\.]?[0-9]{4,6}\$"
val pattern = Pattern.compile(regex)
val matcher = pattern.matcher(phoneNumber)
var contact: Contact? = null
if (matcher.matches() && userDisplayName != null && !userDisplayName.isEmpty()
&& phoneNumber != null && !phoneNumber.isEmpty()
) {
contact = Contact(userDisplayName, phoneNumber)
}
myContacts.add(contact)
}
} while (cursor.moveToNext())
}
runOnUiThread {
Toast.makeText(this@MainActivity, " first contact "+myContacts.get(0)?.number, Toast.LENGTH_LONG).show()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment