This question already has answers here:
How To Test If Cursor Is Empty in a SQLiteDatabase Query

(6个答案)


在12个月前关闭。




当我尝试从电话的联系人列表中获取电话号码时。问题是,当我在手机中的联系人列表为空时运行该应用程序时,该应用程序已停止。我检查了一下,这是因为游标为空。

如何检查光标是否为空或电话的联系人列表中是否有任何联系人?
ArrayList<String> lstPhoneNumber = new ArrayList<String>();
Cursor phones = getContentResolver().query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
lstPhoneNumber = new ArrayList<String>();

phones.moveToFirst();
// The problematic Line:
lstPhoneNumber.add(phones.getString(phones.getColumnIndex(
        ContactsContract.CommonDataKinds.Phone.NUMBER)));
while (phones.moveToNext()) {
    lstPhoneNumber.add(phones.getString(phones.getColumnIndex(
            ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phones.close();

最佳答案

我添加了一个投影,所以您只会得到所需的列。

String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
ArrayList<String> lstPhoneNumber = new ArrayList<String>();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        projection, null, null, null);
if (phones == null)
    return; // can't do anything with a null cursor.
try {
    while (phones.moveToNext()) {
        lstPhoneNumber.add(phones.getString(0));
    }
} finally {
    phones.close();
}

10-07 19:21
查看更多