How to avoid duplicate contact name (data ) while loading contact info to listview?

前端 未结 7 1555
孤独总比滥情好
孤独总比滥情好 2020-12-09 10:58

I am populating contact list details to list view successfully. My code:

  String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + \" ASC\";
         


        
7条回答
  •  一向
    一向 (楼主)
    2020-12-09 11:36

    You need to retrieve the data from the Cursor to HashSet (which don't allows duplicate itmes) and then pass the HashSet object to your ListView's Adapter

    This is a dump solution but it will help you:

    ListView listView;
    Set listItems;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        listItems = new HashSet();
    
        String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
        Cursor curLog =  getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,order); 
    
        if(curLog != null) {
            while(curLog.moveToNext()) {
                String str = curLog.getString(curLog.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
                listItems.add(str);
            }
        }
    
        String listString = listItems.toString();
        listString = listString.substring(1,listString.length()-1);
        String[] newList = listString.split(", ");
    
        ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, newList);
        listView.setAdapter(adapter);        
    }
    

    Good luck..

提交回复
热议问题