To study android development, I have created an android application called "Contacts", it's basically just a phonebook. I have a list of contacts with first name, last name and phone number. I also have an edittext which I use for filtering the list.
Currently, I can filter the list by finding all entries containing the string inputted in the edittext. For example, I have 3 contacts:
Jane Doe
John Doe
John Joseph Smith
If I input something like "oe", the list will return John Doe and Jane Doe. Now, I was hoping I could filtering by the initials of the name so if I enter "J S" or "Jo J S", it would return John Joseph Smith but I'm not entirely sure how to start this implementation.
I've overrided FilterResults performFiltering and this is what I ended up with:
FilterResults results = new FilterResults();
ArrayList<Contacts> filteredContacts= new ArrayList<Contacts>();
if (constraint!= null && constraint.toString().length() > 0) {
for (Contacts contact : unfilteredContacts) {
String firstname = contact.getFirstname();
String lastname = contact.getLastname();
String phone = contact.getNumber();
if (firstname .toLowerCase().contains(constraint.toString().toLowerCase()) ||
lastname .toLowerCase().contains(constraint.toString().toLowerCase()) ||
phone .contains(constraint.toString())) {
filteredContacts.add(contact);
}
}
results.values = filteredContacts;
results.count = filteredContacts.size();
What is the best approach in implementing this? Is there any way I can avoid using nested loops for this?
[UPDATE] I ended up using loops for my implementation however my code is acting a bit funny. I've added this snippet to perform the additional filter:
String[] splitName = fullname.toLowerCase().split(" ");
String[] initials = constraint.toLowerCase().split(" ");
if (initials.length > 1) {
for (String nm : splitName) {
for (String ini : initials) {
if (nm.startsWith(ini)) { isMatch = true; }
else { isMatch = false; }
}
}
}
if (isMatch) { filteredContacts.add(contact); }
If I enter "J D", it only returns "Jane Doe" even though it should also display "John Doe". What's up with that?