从电话簿获取联系人姓名使用号码 - Android
问题描述:
我正在处理短信应用程序,我需要显示SMS发件人的姓名。 例如,如果有人发送消息,应用程序将从电话簿中检查其名称,并显示它是否不存在,然后显示空字符串或空字符串。 我尝试了一些代码,但无法获得,这是错误的。从电话簿获取联系人姓名使用号码 - Android
Exception smsReceiverandroid.database.CursorIndexOutOfBoundsException: After last row.
这里是代码:
String displayName="";
//Resolving the contact name from the contacts.
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(senderNum));
Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null);
try {
c.moveToFirst();
displayName = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//displayName = c.getString(0);
String ContactName = displayName;
Log.i("com.azeem.Debug", displayName);
Log.i("com.azeem.Debug", ContactName);
Toast.makeText(context, ContactName, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}finally{
c.close();
}
senderNum
是一个数字,人谁正在发送短信。 您能否让我知道有关错误,看起来我试图访问index
,这是不可用,但我能做些什么来获得联系人名称
答
我检查了你的代码它工作正常。你需要在得到任何东西之前检查你的cursor
。
这是我的代码检查了这一点。
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(senderNum));
Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null);
try {
if(c.moveToFirst()) {
displayName = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//displayName = c.getString(0);
String ContactName = displayName;
Log.i("com.azeem.Debug", displayName);
Log.i("com.azeem.Debug", ContactName);
Toast.makeText(context, ContactName, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
c.close();
}
请点击此链接:HTTPS://developer.android.com/training/contacts-provider/retrieve-names.html#NameMatch – ashish
我想你应该检查光标的大小... –