【问题标题】:How can I query contact information based on a phone number如何根据电话号码查询联系信息
【发布时间】:2010-07-14 19:32:51
【问题描述】:

我正在尝试根据 android 1.6 上的电话号码查询联系信息。这是我尝试过的代码。但我的光标中的计数等于 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);

你知道它为什么不工作吗?

谢谢。

【问题讨论】:

标签: android android-1.6-donut


【解决方案1】:

您可以指定一个 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
}

【讨论】:

  • 这是查询联系人的最简单的方法。我做了很多研究并发现了很多方法来做到这一点,但这是迄今为止最简单的。谢谢!
【解决方案2】:

电话号码存储在自己的表中,需要单独查询。要查询电话号码表,请使用 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 的教程

【讨论】:

    猜你喜欢
    • 2011-03-13
    • 2013-02-11
    • 1970-01-01
    • 2014-11-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2016-08-15
    相关资源
    最近更新 更多