I just want to invite friends to my application so that they can use the application too. For this i get all the contacts but the problem is contacts are repeating. Some contacts are showing 2 times and some are 3 and 4 times. I think i should a query "group by" so that no duplicates will be shown but I am confused where to put that query. Here is my code:
private ArrayList<String> conNames;
private ArrayList<String> conNumbers;
private Cursor crContacts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.invite);
conNames = new ArrayList<String>();
conNumbers = new ArrayList<String>();
crContacts = ContactHelper.getContactCursor(getContentResolver(), "");
crContacts.moveToFirst();
while (!crContacts.isAfterLast()) {
conNames.add(crContacts.getString(1));
conNumbers.add(crContacts.getString(2));
crContacts.moveToNext();
}
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1,
R.id.tvNameMain, conNames));
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource, int textViewResourceId,
ArrayList<String> conNames) {
super(context, resource, textViewResourceId, conNames);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = setList(position, parent);
return row;
}
private View setList(int position, ViewGroup parent) {
LayoutInflater inf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inf.inflate(R.layout.liststyle, parent, false);
TextView tvName = (TextView) row.findViewById(R.id.tvNameMain);
final TextView tvNumber = (TextView) row.findViewById(R.id.tvNumberMain);
tvName.setText(conNames.get(position));
tvNumber.setText(conNumbers.get(position));
return row;
}
}
Guide me what to do avoid duplicate contacts
@Arslan Ali
If you don't want duplicates in a Collection, you should consider using HashMap
. It does not allow duplicate keys however it allows to have duplicate values. So since your fetching the contacts name
and number
. Number will always be unique so make number your key and name as your value.
so in your case
Map<String, String> hm = new HashMap<String, String>();
while (!crContacts.isAfterLast()) {
hm.put(crContacts.getString(2),crContacts.getString(1));
crContacts.moveToNext();
}
So this way you will never have repetitive contacts. Now iterate through you HashMap
and then push your key value to conNumbers
and name value to conNames
for (String key : hm.keySet()) {
conNames.add(key);
conNumbers.add(hm.get(key));
}
And you got your unique Arraylist.