Android 正在获取选定联系人的手机号码
我想检索所选联系人的。但不返回任何内容,因为它生成运行时异常Android 正在获取选定联系人的手机号码,android,contacts,Android,Contacts,我想检索所选联系人的。但不返回任何内容,因为它生成运行时异常 String[] Phoneprojection = {Phone.NUMBER,Phone.TYPE}; String[] projection ={Contacts.DISPLAY_NAME}; String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"; C
String[] Phoneprojection = {Phone.NUMBER,Phone.TYPE};
String[] projection ={Contacts.DISPLAY_NAME};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1";
Cursor cursor = null;
Cursor phone = null;
try
{
cursor = managedQuery(intent.getData(), projection, selection, null, null);
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
phone = managedQuery(Phone.CONTENT_URI,Phoneprojection,Data.CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)},
null);
if(phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);
while(!phone.isAfterLast()) {
final String number = phone.getString(contactNumberColumnIndex);
//final int type = phone.getInt(contactTypeColumnIndex);
//final int typeLabelResource = Phone.getTypeLabelResource(type);
// if(typeLabelResource==2)
phonenumber.setText(number);
Log.e("TAG1",phonenumber.toString());
phone.moveToNext();
}
}
}
}
catch (Exception npe)
{
Log.e("TAG2", "Error trying to get Contacts."+npe.getMessage());
}
生成的日志为:
尝试获取联系人时出错。无法从游标窗口读取第0行第1列。在从光标访问数据之前,确保光标已正确初始化。
谁能告诉我如何解决这个问题。您可以立即访问外部光标,但您甚至不确定它是否实际返回了数据
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
将While循环更改为do-While-one和call
if (!cursor.moveToFirst())
return;
这将确保您的查询实际得到一个结果。您的代码是错误的。没有联系人。\u ID包含在您的投影中
String[] projection ={Contacts.DISPLAY_NAME}; // add Contacts._ID if you wanna query it
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));