How to show phone contacts in a ListView

后端 未结 2 1817
面向向阳花
面向向阳花 2020-12-18 12:45

Following is my code, actually on screen it\'s not showing me any contact. In emulator I have 5 contacts added. Please tell me what to do.

{
    //some code
         


        
相关标签:
2条回答
  • 2020-12-18 13:05

    I have copied and executed almost the same code and it works:

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Cursor cur = getContacts();
    
            ListView lv = getListView();
    
           String[] fields = new String[] {ContactsContract.Data.DISPLAY_NAME};
    
           SimpleCursorAdapter adapter = 
                    new SimpleCursorAdapter(this, 
                                            R.layout.main,
                                            cur,
                                            fields,
                                            new int[] {R.id.txtbox});
              lv.setAdapter(adapter);         
        }    
    
        private Cursor getContacts() {  
            // Run query     
            Uri uri = ContactsContract.Contacts.CONTENT_URI;
    
            String[] projection = 
                    new String[]{ ContactsContract.Contacts._ID,
                                  ContactsContract.Contacts.DISPLAY_NAME }; 
                String selection = null;
                String[] selectionArgs = null;  
                String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + 
                    " COLLATE LOCALIZED ASC";  
                return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
        }
    

    Please check if you have done anything wrong in the textview implementation?

    0 讨论(0)
  • 2020-12-18 13:14

    First I would just narrow the problem.

    1) Check if you have permissions for reading contacts

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

    2) Check if cursor have any results

    cur.getCount()
    
    0 讨论(0)
提交回复
热议问题