Search code examples
androidandroid-recyclerviewandroid-contentproviderandroid-contactsandroid-contentresolver

Show only a certain number of contacts


I have developed a program that shows a list of contacts from my phone book. For this I use the following code:

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null,
            ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'",
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
           Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(id)); 
            Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                    null,
                    null);
            if (phones != null) {
                    while (phones.moveToNext()) {
                        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        contactList.add(new Contact(name, phoneNumber, id));
                    }

                phones.close();
            }
        }
        cursor.close();
    }
    adapter = new ContactAdapter(contactList, R.layout.contacts_list_item, getApplicationContext());
    recyclerView.setAdapter(adapter);

Everything works, and the program displays all contacts from my phone book, but I want a certain number of contacts to be displayed. For example: I open the program and load the first 50 contacts from the phone book, after scrolling, the next 50 contacts are loaded to the end of the list. and so on


Solution

  • Use below code that has limit cause. Replace your code with below

    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null,
                ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1' ",
                null,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC LIMIT 10");
    

    It will get first 10 records. And in pull to refresh implementation, get more records on call back event of pull to refresh. Hope this will help you