我想从我尝试通过查询检索它的号码中获取联系人姓名但是我没有得到结果..它正在返回号码本身.....我已经将该号码保存到联系人
我尝试的代码是......
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String x = getContactNameFromNumber("+918281306132");
System.out.println(x);
}
private String getContactNameFromNumber(String number) {
// define the columns I want the query to return
System.out.println("Entering into getContactNameFromNumber");
String[] projection = new String[] {
Contacts.Phones.DISPLAY_NAME,
Contacts.Phones.NUMBER };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(number));
// query time
Cursor c = getContentResolver().query(contactUri, projection, null,
null, null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(Contacts.Phones.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}
}
我也添加了一个读取手机状态权限。有人请帮我检索联系人姓名。
答案 0 :(得分:1)
在代码中进行以下更改
Uri contactUri = Uri.withAppendedPath(Phone.CONTENT_URI, Uri.encode(number));
和
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
return name;
}
尝试一下,希望它会对你有所帮助。 :)
答案 1 :(得分:0)
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println(name + "name");
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
}
}
此代码正在为我工作
答案 2 :(得分:0)
您可以尝试我的代码段:
public static String findContactByNumber(String phoneNumber,
ContentResolver cr) {
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
String[] phoneNoProjections = { PhoneLookup._ID,
PhoneLookup.DISPLAY_NAME };
Cursor cursor = cr.query(lookupUri, phoneNoProjections, null, null,
null);
try {
if (cursor.moveToFirst()) {
return cursor.getString(1); //1 is the display name index. 0 is id.
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}