How to check if a cursor is empty?

android, android-contacts, android-cursor

Solution

I added in a projection so you are only getting the column you need.

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();
}

Problem

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(); ```

Original source

Related problems