Android从联系人列表中获取电话号码
作者:互联网
我有这些代码基本上使用ListView来显示联系人列表中的名称,我想在单击每个单一名称时获取他们的电话号码:
final ContentResolver cr = getContentResolver();
final Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {ContactsContract.Contacts.DISPLAY_NAME}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);
myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
c.moveToPosition(position);
Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)), Toast.LENGTH_SHORT).show();
}
});
在onItemClick方法中
GetColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
返回-1,因此我无法使用此方法获取电话号码.
我还尝试打印出光标c的所有列,它返回34列,但唯一与电话号码相关的列是HasPhoneNumber.
那么问题在哪里,我该如何解决?谢谢!
更新版本,其中传递给构造myCursorAdapter的String数组已更改:
final ContentResolver cr = getContentResolver();
final Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);
myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
c.moveToPosition(position);
Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)), Toast.LENGTH_SHORT).show();
}
});
我想更新后的代码会在ListView中显示电话号码,但我收到一条错误,说“列’data1’不存在”.
解决方法:
ContactsContract Android API在“数据”表中存储有关电话号码等联系人的数据,而不是“联系人”表.
仔细阅读:https://developer.android.com/reference/android/provider/ContactsContract.html.
更新 – 这是您的代码的固定版本(未经测试):
final ContentResolver cr = getContentResolver();
String[] projection = new String[] {Contacts.DISPLAY_NAME, Phone.NUMBER};
final Cursor c = cr.query(Data.CONTENT_URI, projection, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {Phone.NUMBER}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);
myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
c.moveToPosition(position);
Toast.makeText(getApplicationContext(), c.getString(1), Toast.LENGTH_SHORT).show();
}
});
标签:android,android-contacts 来源: https://codeday.me/bug/20190828/1754982.html