我正在尝试创建一个应用程序,从联系人中选择联系人并在屏幕上显示姓名和号码。到目前为止,我已创建活动来选择联系人,活动已成功返回联系人。它成功显示了联系人姓名。现在我在显示数字时遇到问题。有各种各样的解决方案,我想要最简单的解决方案。所有这些都经历了复杂的方法,这对我来说很难理解。我无法找到一个可以显示ContactsContract.Contacts.DISPLAY_NAME
这是我的代码!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_contact);
Intent viewContact = getIntent();
String tempViewContact = viewContact.getStringExtra(MainActivity.contactUri);
Uri contactUri = Uri.parse(tempViewContact);
Cursor cursor;
cursor = getContentResolver().query(contactUri,null,null,null,null);
cursor.moveToFirst();
int indexName = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int indexID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
//Shows Contact name
String contactName = cursor.getString(indexName);
contact_name = (TextView) findViewById(R.id.contact_name);
contact_name.setText(contactName);
contact_num = (TextView) findViewById(R.id.contact_number);
//Now what to do ????
}
答案 0 :(得分:1)
以下是有关如何从设备收集联系人的小片段
// Getting Content Resolver to Access Contact Details
ContentResolver cr = c.getContentResolver();
// Getting Cursor
Cursor cur1 = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
// Checking CURSOR HAS DATA
if (cur1.getCount() > 0) {
// LOOPING THROUGH EVERY CONTACT
while (cur1.moveToNext()) {
// GETTING CONTACT ID
String id = cur1.getString(cur1
.getColumnIndex(ContactsContract.Contacts._ID));
// GETTING CONTACT NAME
String contactName = cur1
.getString(cur1
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactNumber = "";
// Ensuring number availablity
if (Integer
.parseInt(cur1.getString(cur1
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Phone numbers are stored in another table
// Cursor for Phone Numbers
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
// Has Number in Cursor - CHECK + LOOP
while (pCur.moveToNext()) {
// Checking Number Count for A SINGLE
// CONTACT
if (pCur.getCount() > 1) {
contactNumber = contactNumber
+ ","
+ pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} else {
contactNumber = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
}
// LOGGING
Log.d("X", "ID:" + id + "\nName:" + contactName
+ "\nNumber:" + contactNumber);
Log.i("X", "--------------------------------");
在清单中包含以下权限
<uses-permission android:name="android.permission.READ_CONTACTS" />
如果要在列表中显示姓名和联系电话号码,请按照以下步骤进行操作
1)建立一个包含两个字段名称的模型类,联系人说ContactModel
2)创建一个ContactModel列表并将每个模型添加到列表中。
3)最后使用自定义适配器将数据附加到listView。