我创建了一个包含三个变量的自定义ContactsRow class
。我将此类的对象添加到ArrayList
逐个。我想要实现的是,每当我向ArrayList
添加新对象时,它应检查该对象是否已添加到列表中。我使用contains()
方法来检查相同的内容。但是,当我运行我的应用程序时,从不调用此方法,并且我在列表中获得重复值。
这是我的ContactsRow class
:
private class ContactsRow {
String name, phone;
Bitmap photo;
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
ContactsRow row = (ContactsRow) obj;
return (name.equals(row.name) || (name != null && name.equals(row.name))) &&
(phone.equals(row.phone) || (phone != null && phone.equals(row.phone))) &&
(photo.equals(row.photo) || (photo != null && photo.equals(row.photo)));
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (name == null ? 0 : name.hashCode());
hash = 31 * hash + (phone == null ? 0 : phone.hashCode());
hash = 31 * hash + (photo == null ? 0 : photo.hashCode());
return hash;
}
public ContactsRow(String name, String phone, Bitmap photo) {
this.name = name;
this.phone = phone;
this.photo = photo;
}
}
以下是我在ArrayList
中添加和检查值的方式:
contactsRow = new ContactsRow(contactName, contactNumber, contact_Photo);
if(contactsRowList.contains(contactsRow)){
AlertDialog.Builder duplicateBuilder = new AlertDialog.Builder(MyContactsActivity.this);
duplicateBuilder.setTitle("Duplicate contact");
duplicateBuilder.setMessage("This contact is already added to list. Please choose unique contact");
duplicateBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, REQUEST_CONTACT);
duplicateEntryDialog.dismiss();
}
});
duplicateEntryDialog = duplicateBuilder.create();
duplicateEntryDialog.show();
} else {
contactsRowList.add(contactsRow);
contactsInfoAdapter.notifyDataSetChanged();
}
永远不会调用此AlertDialog
。
任何人都可以帮我识别问题????