Android的使用名字来取得联络号码 [英] Android get contact number using name
本文介绍了Android的使用名字来取得联络号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Android,是以联系人姓名作为一个字符串输入,并返回他的电话号码,如果该联系人在电话簿中存在的应用程序...
I am trying to make an application on android that takes the contact name as a string input and returns his phone number if that contact exists in the phone book...
我试过各地寻找,但没有明确的教程就如何做到这些。
I tried searching around but there is no clear tutorial as to how to do exactly that
输入:联系人姓名
输出:电话号码
input:contact name outputs:the phone number
请帮忙
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if(name.equalsIgnoreCase(token3)) {
try{ ContentResolver cr = context.getContentResolver();
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { ContactsContract.CommonDataKinds.Phone._ID}, null);
String lname = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(context, "number is "+lname, Toast.LENGTH_LONG).show();
}catch (Exception e) {
// TODO: handle exception
}
}
}
这是我迄今。在try catch块片code总是崩溃。
it's what I have so far. the piece of code in the try catch block always crashes.
推荐答案
我写了这个方法,最终解决我的问题。
I wrote this method eventually to solve my problem
public String get_Number(String name,Context context)
{String number="";
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = context.getContentResolver().query(uri, projection, null, null, null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
people.moveToFirst();
do {
String Name = people.getString(indexName);
String Number = people.getString(indexNumber);
if(Name.equalsIgnoreCase(name)){return Number.replace("-", "");}
// Do work...
} while (people.moveToNext());
if(!number.equalsIgnoreCase("")){return number.replace("-", "");}
else return number;
}
它可能不是非常有效,但嘿它的工作原理
it may not be very efficient but hey it works
这篇关于Android的使用名字来取得联络号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文