无法使用联系人ID检索姓名和号码

时间:2015-05-24 05:30:46

标签: java android

我正在尝试使用存储在数据库中的id检索联系人的姓名和号码,但是在尝试false时,游标会返回cursor.moveToFirst()。这是代码 -

Log.d(TAG, id);
Cursor cursor = this.getContentResolver().query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        null,
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
        new String[]{id}, null);
if(cursor == null){
    return;
}
while (cursor.moveToFirst())
{
    try{
        number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    }catch (NullPointerException e){
        number = "";
    }
    try{
        name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    }catch (NullPointerException e){
        name = "No name";
    }
}
cursor.close();

注意 - ID是正确的。我已经使用日志语句进行了检查。

初始化光标后,执行会直接跳至cursor.close()。在调试和检查时,我发现while语句失败,因为cursor.moveToFirst()返回false。

1 个答案:

答案 0 :(得分:0)

  

cursor.moveToFirst()返回false表示没有与ur匹配的数据   查询。对于构造检查cursor.getCount()来检查数据是什么   是否有。