0

i have code java android studio to show list contact in hp and it's permission done, but it's not working (blank value) in sdk >27 anyone help me? this is my code

    contactModelArrayList = new ArrayList<>();
    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null,
            ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'",
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" COLLATE LOCALIZED ASC");
    while (phones.moveToNext())
    {
        String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        ContactModel contactModel = new ContactModel();
        contactModel.setName(name);
        contactModel.setNumber(phoneNumber);

        contactModelArrayList.add(contactModel);


        Log.d("name>>",name+" "+phoneNumber);
    }
    Log.d("phones", phones.toString());
    phones.close();

    contactAllAdapter = new ContactAllAdapter(this,contactModelArrayList);
    listView.setAdapter(contactAllAdapter);

in logcat thereis nothing

Arif MH
  • 21
  • 8
  • do you want a list of all **phones** on the device, or all **contacts**? these are two different things, as you might have contacts w/o any phone, or contacts with multiple phones – marmor Jan 28 '19 at 14:58
  • sorry for the confusion, i want list all contact in my phone + there is no duplicate contacts @marmor can you help me, please? – Arif MH Jan 29 '19 at 03:35

2 Answers2

4

Create your MyCircleContactListData class like this

public class MyCircleContactListData {
    @SerializedName("name")
    @Expose
    public String name;
    @SerializedName("img_url")
    @Expose
    public String imgUrl;

    @SerializedName("mobile_no")
    @Expose
    public String mobileNumber;
}

And then create Contact Accessing Java Class with Contact list return type method getContacts which returns list of your contacts.

 public class GetContactFromDevice {
    private static final String TAG  = "GetContactFromDevice";

    public ArrayList<MyCircleContactListData> getContacts(Context context) {
        ArrayList<MyCircleContactListData> list = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
                            ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));

                    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
                    Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

                    Bitmap photo = null;
                    if (inputStream != null) {
                        photo = BitmapFactory.decodeStream(inputStream);
                    }
                    while (cursorInfo.moveToNext()) {

                        MyCircleContactListData info = new MyCircleContactListData("", "", "", "", false);
                        info.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        info.mobileNumber = TextUtils.validatePhoneNumber(cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                        info.imgUrl= pURI.toString();
                        list.add(info);

                        Log.d("GetContactFromDevice", "getContacts: " + info.name);
                        Log.d("GetContactFromDevice", "getContacts: " + info.mobileNumber);
                    }

                    cursorInfo.close();
                }
            }
            cursor.close();
        }
        return list;
    }

}

Don't forget to provide contact access permission

<uses-permission android:name="android.permission.READ_CONTACTS" />

Then display your contact list.

GetContactFromDevice getContactFromDevice = new GetContactFromDevice();
contactAllAdapter = new ContactAllAdapter(this,getContactFromDevice.getContacts(this));
listView.setAdapter(contactAllAdapter);
Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43
Samir Dangal
  • 2,591
  • 2
  • 15
  • 17
  • do you know how to make it diplay contact without double? – Arif MH Jan 29 '19 at 05:46
  • Check number is already exist or not , and if already exist then dont add. If the number is new and then add to the list. `boolean alreadyExist = false;` `int itemPosition = 0;` `for (int i = 0; i < yourList.size(); i++) { itemPosition = i; if (list.get(i).getMobileNumber().equals(info.mobileNumber)) { alreadyExist = true; break; } else { alreadyExist = false; list.add(info) } }` – Samir Dangal Jan 29 '19 at 06:06
0

You can try LoaderManager

Create following fields

private static final int CONTACTS_LOADER_ID = 101;

private static final String[] PROJECTION = {
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
        ContactsContract.CommonDataKinds.Phone.NUMBER
};

Create follwoing class

public class Contact {

    private String id;
    private String name;
    private String number;

    public Contact(String id, String name, String number) {
        this.id = id;
        this.name = name;
        this.number = number;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

}

[1] Create instance of LoaderManager.LoaderCallback

private LoaderManager.LoaderCallbacks<Cursor> loaderCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {

            switch (id) {
                case CONTACTS_LOADER_ID:

                    return new CursorLoader(
                            getActivity(),
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            PROJECTION,
                            null,
                            null,
                            ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC"
                    );
                default:
                    return null;
            }
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            switch (loader.getId()) {
                case CONTACTS_LOADER_ID:

                   //Use ContactUtils class here


                    break;
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };

[2] Use following class to convert cursor data to List<Contact>

import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;

import java.util.ArrayList;
import java.util.List;

public class ContactUtils {

    private ContactUtils() {
    }

    public static List<Contact> parseContacts(Cursor cursor) {
        List<Contact> contacts = new ArrayList<>();

        if (cursor.getCount() == 0) {
            return contacts;
        }

        int nameColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY);
        int idColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
        int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

        while (cursor.moveToNext()) {
            String contactName = cursor.getString(nameColumnIndex);
            String id = cursor.getString(idColumnIndex);
            String number = cursor.getString(numberColumnIndex);

            Contact contact = new Contact(id, contactName, number);
            if(!isContactAddedInList(contact, contacts)){
                contacts.add(contact);
            }

        }

        return contacts;
    }

public boolean isContactAddedInList(Contact contact, List<Contact> contacts) {

    for (Contact listContact : contacts
            ) {
        if (listContact.number.equals(contact.name)) {
            return true;
        }
    }

    return false;
}


}

[3] Call getLoaderManager().initLoader method to load contacts in your Fragment or Activity's onStart method

getLoaderManager().initLoader(CONTACTS_LOADER_ID, null, loaderCallbacks);
  • Add <uses-permission android:name="android.permission.READ_CONTACTS" /> permission in menifest file
  • You need to ask for runtime permission before calling getLoaderManager().initLoader
Dhaval
  • 2,724
  • 2
  • 24
  • 33
  • do you know how to make it diplay contact without double? – Arif MH Jan 29 '19 at 05:46
  • Do you mean without duplicate contact? – Dhaval Jan 29 '19 at 05:47
  • You can add that logic in parseContacts method of ContactUtils class. You can check if the number has already added in contacts(list), then don't add it in list. – Dhaval Jan 29 '19 at 05:52
  • can you give me example for that? because I still lack experience for that – Arif MH Jan 29 '19 at 05:54
  • I have updated the answer. Please check isContactAddedInList method. – Dhaval Jan 29 '19 at 06:17
  • hehehe, thankyou daval for your help. but sorry, I am confused about how to put the correct function, so that my code becomes an error :') – Arif MH Jan 29 '19 at 06:53
  • I think you need a full demo of loading contacts and displaying it in RecyclerView. This is out of the scope of this answer but I will post the link of some tutorial if I find any. – Dhaval Jan 29 '19 at 06:56
  • You can find the complete example here. It is my github repo of AndroidTutorials. https://github.com/dhavalshah05/AndroidTutorials/blob/master/app/src/main/java/com/itgosolutions/tutorial/contacts/FragmentContacts.java – Dhaval Jan 29 '19 at 07:11