What is the best way to get distinct contacts in Android

后端 未结 4 1519
南旧
南旧 2020-12-17 02:34

I am successfully storing contacts in parse.com dashboard data browser by this code.

public void readContacts(){
         ContentResolver cr = getContentReso         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 02:49

    An easy approach could be to load the data to a MatrixCursor with no duplicate data. For example lets assume you have a cursor c1 will many contacts, but you need a cursor with no duplicate data. Here is what you could do:

    MatrixCursor mc = new MatrixCursor(new String[] { 
                            Phone._ID, 
                            Phone.DISPLAY_NAME_PRIMARY,
                            Phone.NUMBER
    });
    
    String lastNumber = "";
    
    while(c1.moveToNext()){
        String id = c1.getString(c1.getColumnIndexOrThrow(Phone._ID));
        String name = c1.getString(c1.getColumnIndexOrThrow(Phone.DISPLAY_NAME_PRIMARY)));
        String number = c1.getString(c1.getColumnIndexOrThrow(Phone.NUMBER));
    
        //Some condition to check previous data is not matched and only then add row
        if(!lastNumber.contains(number)){
                lastNumber = number;
                mc.addRow(new String[]{id, name, number});
        }
    
    
    }
    
    c1.close();
    

    Make an instance of MatrixCursor with same columns, and then load if last number or contact name does not match that of the previous contact. The condition for checking is upto you. Query data in some order so that the duplicate contacts stay together first.

    Once the MatrixCursor is loaded you can fetch data from it. You could also attach it to a view through a custom CursorLoader or CursorAdapter.

提交回复
热议问题