【发布时间】:2022-01-15 23:34:03
【问题描述】:
在一个聊天应用上工作,我想获取用户(B、C、D、..)的列表,其联系人保存在用户(A)手机中。
首先,我从手机中获取用户 (A) 联系人并将它们存储在 ArrayList (phoneContactArrayList) 中。其次,我获取在我的应用上注册的用户电话号码,并将它们存储在 ArrayList (dbContactArrayList) 中。
现在我想比较这两个数组列表并从中获取常用联系人号码,即在我的应用程序上注册的用户 (A) 的联系人 (B, C, D,...) 和用户 (A) 可以通过我的应用与他们联系。
这里是从 User(A) 手机中获取联系人的方法。
private fun getContactList() {
phoneContactArrayList = ArrayList()
val cr = contentResolver
val cur = cr.query(
ContactsContract.Contacts.CONTENT_URI,
null, null, null, null
)
if (cur?.count ?: 0 > 0) {
while (cur != null && cur.moveToNext()) {
val id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID))
val name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
val pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
arrayOf(id), null
)
while (pCur!!.moveToNext()) {
phoneContactArrayList?.clear()
val phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
phoneContactArrayList!!.add(phoneNo)
Log.i("Users Ph.Contacts List=" , phoneContactArrayList.toString())
// all users contacts are shown successfully as I check in Logcat
}
pCur.close()
}
}
}
cur?.close()
}
这是通过 Firebase 身份验证获取在我的应用上注册的用户的方法。
private fun getFirebaseContacts() {
dbContactArrayList = ArrayList()
FirebaseDatabase.getInstance().getReference("UserProfile")
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(contactList: DataSnapshot) {
try {
dbContactArrayList?.clear()
for (eachContactList in contactList.children) {
// Log.e("TAG", "onDataChange: " + eachContactList.value.toString())
var contactModel: SignUpEntity =
eachContactList.getValue(SignUpEntity::class.java)!!
val mData = contactModel.userPhone
if (mData != null) {
dbContactArrayList?.add(mData)
}
Toast.makeText(applicationContext,"Firebase Users List=${dbContactArrayList.toString()}",
Toast.LENGTH_SHORT
).show() // successfully toast the numbers registered on app
}
} catch (e: Exception) {
//Log.e("Exception",e.toString())
}
}
override fun onCancelled(p0: DatabaseError) {
TODO("Not yet implemented")
}
})
}
这里是比较两个ArrayList得到共同联系人的方法,resultArrayList总是空的。
private fun getMatchedContacts(dbContactArrayList: ArrayList<String>?, phoneContactArrayList: ArrayList<String>?) { // here on debugging I get to know both arrayLists are of size 0.
resultArrayList = ArrayList()
for (s in phoneContactArrayList!!) {
resultArrayList?.clear()
if (dbContactArrayList!!.contains(s) && !resultArrayList!!.contains(s)) {
resultArrayList!!.add(s)
}
}
Log.e("Result Values", resultArrayList.toString())
}
【问题讨论】:
标签: android firebase kotlin firebase-realtime-database