2010-07-14 92 views
1

我想查询基于Android 1.6上的电话号码的联系信息。这是我试过的代码。但是在我的光标中,我得到count等于0。我如何查询基于电话号码的联系信息

String selection = "PHONE_NUMBERS_EQUAL(" + People.Phones.NUMBER + " , " + phoneNumber + ")"; 
    Cursor cursor = mContext.getContentResolver().query(People.CONTENT_URI, 
      new String[] {People._ID, People.NAME, People.Phones.NUMBER}, 
      selection, null, null); 

你知道为什么它不起作用吗?

谢谢。

+0

的重复[有没有一种简单的方法来检查,如果来话主叫方是联系在Android?](http://stackoverflow.com/questions/2193664/is-there-a-simple-way-to-check-if-an-incoming-caller-is-a-contact-in-android) – 2010-12-18 18:26:46

回答

4

您可以指定一个URI并使用查询直接拿到电话号码的联系人信息..

Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(phoneNumber)); 

Cursor cursor = mContext.getContentResolver().query(contactUri, null, null, null, null); 

通过上面的代码返回的光标会那么包含你正在寻找的接触,你可以得到你所需要的信息了...

if(cursor.moveToFirst()){ 
    int personIDIndex = cursor.getColumnIndex(Contacts.Phones.PERSON_ID); 
    //etc 
} 
+0

这是查询联系人的最简单方法。我做了很多研究,发现了很多方法来做到这一点,但这是迄今为止最简单的方法。谢谢! – Nick 2013-08-29 04:48:43

1

电话号码存储在自己的表中,需要单独查询。要查询电话号码表,请使用存储在SDK变量Contacts.Phones.CONTENT_URI中的URI。使用WHERE条件来获取指定联系人的电话号码。

if (Integer.parseInt(cur.getString(
     cur.getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) { 
    Cursor pCur = cr.query(
      Contacts.Phones.CONTENT_URI, 
      null, 
      Contacts.Phones.PERSON_ID +" = ?", 
      new String[]{id}, null); 
    int i=0; 
    int pCount = pCur.getCount(); 
    String[] phoneNum = new String[pCount]; 
    String[] phoneType = new String[pCount]; 
    while (pCur.moveToNext()) { 
     phoneNum[i] = pCur.getString(
          pCur.getColumnIndex(Contacts.Phones.NUMBER)); 
     phoneType[i] = pCur.getString(
          pCur.getColumnIndex(Contacts.Phones.TYPE)); 
     i++; 
    } 
} 

查询电话表并获取存储在pCur中的光标。由于Android联系人数据库可以为每个联系人存储多个电话号码,因此我们需要遍历返回的结果。除了返回电话号码以外,查询还返回了数字类型(家庭,工作,手机等)。

而且阅读本教程的Working With Android Contacts API For 1.6 and Before

相关问题