当我试图从电话的联系人列表中获取电话号码时。问题是,当我在手机中的联系人列表为空的情况下运行应用程序时,应用程序会停止。我检查了一下,这是因为光标是空的。
如何检查光标是否为空,或者电话的联系人列表中是否有联系人?
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();
发布于 2013-02-22 03:50:43
我添加了一个投影,所以你只能得到你需要的列。
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();
}
发布于 2013-02-22 03:40:35
使用cursor.getCount() == 0
。如果为true,则游标为空
发布于 2013-02-22 03:40:45
试试这个吧。代码的问题在于,无论游标的长度如何,它都会执行add。我将phones.moveToFirst()包含在if语句中,因为如果游标为空或没有设置记录,它将返回false。
if(phones.moveToFirst()){
do{
lstPhoneNumber.add(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}while(phones.moveToNext())
} else {
//do something else
}
https://stackoverflow.com/questions/15010761
复制相似问题