When I'm trying to get the phone numbers from the contact list of the phone. The problem is, when I'm running the app while the contact list in the phone is empty, the app is stopped. I checked it and this is because the cursor is empty.
How can I check if the cursor is empty or if there are any contacts in the contact list of the phone?
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();
The general pattern to test for a "valid" cursor is
((cursor != null) && (cursor.getCount() > 0))
The Contacts Provider doesn't return null, but other content providers might do so if they encounter some sort of data error. A content provider should handle Exceptions, set the cursor to zero, and log the Exception, but there's no guarantee.