Optimising AutoCompleteTextView for Android Contacts
I have implemented an autocomplete feature to allow the user to start typing a contact and for that contact to appear in a dropdown list using an autoCompleteTextView, like the same way it works when picking contacts for messages or e-mails.
As I don’t want a variable holding all of the contacts at once since this could be very big, I populated my ArrayList as the user enters letters into the contact field.
I am setting it up like this:- peopleList = new ArrayList>();
adapter = new SimpleAdapter(this, peopleList, R.layout.customcontcell ,new String[] { "Name", "Phone" , "Type" }, new int[] { R.id.ccontName, R.id.ccontNo, R.id.ccontType });
txtPhoneNo.setAdapter(adapter);
Then when the user starts typing a name it grabs all the rows from the Contacts that match that, this is done in my function “QueryContacts” like so:-
selectionWhere = ContactsContract.Contacts.DISPLAY_NAME+" LIKE '" + name + "%'";
//Cursor to retrive contact details.
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, selectionWhere, null, null);
This cursor is then used to populate my peopleList which is being used by the Adapter.
In this state it works, however without some checks the above code ends up retrieving ALL of the contacts initially (as no name is entered so it filters nothing) and it runs every time a new letter is typed. This is jittery and slow.
So I wanted to put some simple checks to limited it to only retrieving the contacts when 2 letters have been entered, and not retrieving anymore unless it goes below 2 letters then back to 2 again.
So around my QueryContacts functions I add:-
if(name.length() < 2)
mGotContacts = false;
//If the length is two letters long and we haven't queried already, query for the name.
if(name.length() == 2 && mGotContacts == false)
{
// Cursor code
// Populate list with cursor data.
}
Problem is now the autocompleteTextView no longer drops down, I have checked and the variable peopleLists which populated my SimpleAdapter is being correctly updated.
So, am I开发者_开发技巧 doing this a daft way? Should I just grab all of the data in one go and let the AutoCompleteTextView filter it?
Is their a better way of doing this and why does it no longer work with those checks in my QueryContacts function?
Have a look at the threshold property of AutoCompleteTextView. The threshold defines the number of characters that must be entered before the autocomplete drop down is shown. I am not sure what effect this would have on performance, but since its native to android I imagine its as fast as reasonably possible. setThreshold method documentation
精彩评论