Search code examples
androidsortingandroid-contacts

sort contacts in android application in Alphabetical order according to display name


i know this question has been asked already but i cant seem to find anything that works for me from the content here and on other web resources. i want to display contacts in alphabetical order according to the DISPLAY NAME but they are sorted according to the number of the contact here is my code.

public class ContactActivity extends Activity implements OnItemClickListener {

    private ListView listview;
    private List<ContactBean> list = new ArrayList<ContactBean>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_list);

        listview = (ListView) findViewById(R.id.list);
        listview.setOnItemClickListener(this);

        Cursor phone = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                null, null);
        while (phone.moveToNext()) {

            String name = phone
                    .getString(phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phone
                    .getString(phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            ContactBean objContact = new ContactBean();
            objContact.setName(name);
            objContact.setPhoneNo(phoneNumber);
            list.add(objContact);
        }
        phone.close();

can any one help me to sort my contacts by rewriting this code thanks in advance.


Solution

  • Figured out what to do, I changed the code to this and it worked fine.

    Cursor cursor = getContentResolver.query(Phone.CONTENT_URI, null, null, null,Phone.DISPLAY_NAME + " ASC");