如何检查游标是否为空?

Yos*_*oof 23 android cursor android-contacts

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

如何检查光标是否为空或手机的联系人列表中是否有任何联系人?

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();
Run Code Online (Sandbox Code Playgroud)

Joe*_*lin 45

测试"有效"光标的一般模式是

((cursor != null) && (cursor.getCount() > 0))
Run Code Online (Sandbox Code Playgroud)

Contacts Provider不会返回null,但如果遇到某种数据错误,其他内容提供商可能会这样做.内容提供程序应该处理异常,将游标设置为零,并记录异常,但不能保证.


Gab*_*han 24

使用cursor.getCount() == 0.如果为true,则光标为空


dym*_*meh 9

我添加了一个投影,因此您只需获得所需的列.

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 完成后,应始终关闭光标. (2认同)

Cao*_*Dat 5

public boolean isCursorEmpty(Cursor cursor){
   return !cursor.moveToFirst() || cursor.getCount() == 0;
}
Run Code Online (Sandbox Code Playgroud)