[英]How Can I list all mobile contacts on an App Android
I started to learn Mobile App Development with Android Studios.我开始使用 Android Studios 学习移动应用程序开发。 I want to create a simple app(for testing) where I display all cellphone contacts in a ListView.
我想创建一个简单的应用程序(用于测试),在 ListView 中显示所有手机联系人。
I have the main activity and its xml file where I have added a ListView element, I want to display all contacts there.我有主要活动及其 xml 文件,我在其中添加了一个 ListView 元素,我想在那里显示所有联系人。
This is the code of the main activity class:这是主要活动class的代码:
package com.example.contactlist;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
this is the code of the main activity XML:这是主要活动 XML 的代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="66dp"
android:background="@color/colorPrimaryDark"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:title="Contact Lists" />
<TextView
android:id="@+id/subtitulo_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact Lists"
android:textColor="@android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.087"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.119" />
<ListView
android:id="@+id/listado_contactos"
android:layout_width="346dp"
android:layout_height="644dp"
android:layout_marginStart="24dp"
android:layout_marginLeft="24dp"
android:layout_marginTop="21dp"
android:layout_marginEnd="23dp"
android:layout_marginRight="23dp"
android:layout_marginBottom="29dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/subtitulo_container"
tools:listitem="@android:layout/simple_list_item_multiple_choice" />
</androidx.constraintlayout.widget.ConstraintLayout>
and this is the code of the AndroidManifest file:这是 AndroidManifest 文件的代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contactlist">
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
What I want to know is how can I get all contacts data from the cellphone and display them in my ListView?我想知道的是如何从手机中获取所有联系人数据并将它们显示在我的 ListView 中?
I've developed a utility class to retrieve device contacts.我开发了一个实用程序 class 来检索设备联系人。 It's available on GitHub:
它在 GitHub 上可用:
Since handling all situations that might happen in retrieving contacts is a bit time consuming, I suggest you get this file and add it to your project.由于处理检索联系人中可能发生的所有情况有点费时,我建议您获取此文件并将其添加到您的项目中。 It's written in
kotlin
, but if you are using java
, also it's possible to get the list of contacts like the following:它是用
kotlin
编写的,但是如果您使用的是java
,也可以获得如下联系人列表:
List<ContactData> contacts = ContactUtilsKt.retrieveAllContacts(context);
// or to retrieve all contacts matching specific search pattern:
List<ContactData> contacts = ContactUtilsKt.retrieveAllContacts(context, "John");
Here is a function from which you can get contacts这是一个 function ,您可以从中获取联系人
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
}
Reference android-get-all-contacts参考android-get-all-contacts
you must push or set list to your adapter您必须将列表推送或设置到您的适配器
public List<String> getNumber(ContentResolver cr)
{
List<String> phonebook = new ArrayList<>();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
// use the cursor to access the contacts
while (phones.moveToNext())
{
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phonebook.add(phoneNumber);
}
return phonebook;
}
I tried with the aceepted answer, but everytime i used to get my list of particluar contactId as 0我尝试了接受的答案,但每次我将我的特定联系人列表列表设为 0
val result: MutableList<ContactData> = mutableListOf()
contentResolver.query(
ContactsContract.Contacts.CONTENT_URI,
CONTACT_PROJECTION,
if (searchPattern.isNotBlank()) "${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} LIKE '%?%'" else null,
if (searchPattern.isNotBlank()) arrayOf(searchPattern) else null,
if (limit > 0 && offset > -1) "${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} ASC LIMIT $limit OFFSET $offset"
else ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC"
)?.use {
if (it.moveToFirst()) {
do {
val contactId = it.getLong(it.getColumnIndex(CONTACT_PROJECTION[0]))
val name = it.getString(it.getColumnIndex(CONTACT_PROJECTION[2])) ?: ""
val hasPhoneNumber = it.getString(it.getColumnIndex(CONTACT_PROJECTION[3])).toInt()
val phoneNumber: List<String> = if (hasPhoneNumber > 0) {
retrievePhoneNumber(contactId)
} else mutableListOf()
val avatar = if (retrieveAvatar) retrieveAvatar(contactId) else null
result.add(ContactData(contactId, name, phoneNumber, avatar))
} while (it.moveToNext())
}
}
return result
for this first part of code as it internally calls retrivePhoneNumber(contactId)对于代码的第一部分,因为它在内部调用retrivePhoneNumber(contactId)
val result: MutableList<String> = mutableListOf()
contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
"${ContactsContract.CommonDataKinds.Phone.CONTACT_ID} =?",
arrayOf(contactId.toString()),
null
)?.use {
if (it.moveToFirst()) {
do {
result.add(it.getString(it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)))
} while (it.moveToNext())
}
}
return result
here in this block of code it.moveToFirst() always false, so returned list is always zero在此代码块中, it.moveToFirst()始终为 false,因此返回的列表始终为零
Here is the working code which will return all list number as list excluding those number who is the same number but space in it like +91123 344 55这是将所有列表编号作为列表返回的工作代码,不包括那些相同编号但其中有空格的编号,例如+91123 344 55
val contactsNumberMap = HashMap<String, HashSet<String>>()
val result: MutableList<String> = mutableListOf()
withContext(Dispatchers.IO) {
context.contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
null,
null,
null
)?.use { c ->
val contactIdIndex =
c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)
val numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
while (c.moveToNext()) {
val contactId = c.getString(contactIdIndex)
val number: String = c.getString(numberIndex)
if (number.contains(' ').not()) {
if (contactsNumberMap.containsKey(contactId)) {
contactsNumberMap[contactId]?.add(number)
} else {
contactsNumberMap[contactId] = hashSetOf(number)
}
}
}
contactsNumberMap.map { m ->
m.apply {
value.forEach {
result.add(it)
}
}
}
}
return@withContext result
}
return result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.