Android - autocomplete with contacts

I created an AutoCompleteTextView window that displays the names of all contacts, but after searching in the Android API it seems that my method is probably quite inefficient.

I am currently grabbing the cursor of all contacts, putting each name and each contact identifier in two different arrays, and then passing an array of names to AutoCompleteTextView. When the user selects an element, I look at which identifier is selected in the second id array created above. Code below:

private ContactNames mContactData; // Fill the autocomplete textbox Cursor contactsCursor = grabContacts(); mContactData = new ContactNames(contactsCursor); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.contact_name, mContactData.namesArray); mNameText.setAdapter(adapter); private class ContactNames { private String[] namesArray; private long[] idsArray; private ContactNames(Cursor cur) { namesArray = new String[cur.getCount()]; idsArray = new long[cur.getCount()]; String name; Long contactid; // Get column id's int nameColumn = cur.getColumnIndex(People.NAME); int idColumn = cur.getColumnIndex(People._ID); int i=0; cur.moveToFirst(); // Check that there are actually any contacts returned by the cursor if (cur.getCount()>0){ do { // Get the field values name = cur.getString(nameColumn); contactid = Long.parseLong(cur.getString(idColumn)); // Do something with the values. namesArray[i] = name; idsArray[i] = contactid; i++; } while (cur.moveToNext()); } } private long search(String name){ // Lookup name in the contact list that we've put in an array int indexOfName = Arrays.binarySearch(namesArray, name); long contact = 0; if (indexOfName>=0) { contact = idsArray[indexOfName]; } return contact; } } private Cursor grabContacts(){ // Form an array specifying which columns to return. String[] projection = new String[] {People._ID, People.NAME}; // Get the base URI for the People table in the Contacts content provider. Uri contacts = People.CONTENT_URI; // Make the query. Cursor managedCursor = managedQuery(contacts, projection, null, null, People.NAME + " ASC"); // Put the results in ascending order by name startManagingCursor(managedCursor); return managedCursor; } 

There should be a better way to do this - basically I'm afraid to see how I can find which item the user selected in the AutoCompleteTextView. Any ideas?

Greetings.

+4
source share
3 answers

Create your own cursor adapter and use it for AutoCompleteTextView.

There is a convertToString () function in the CursorAdapter that needs to be rewritten in order to get the details that you want to display in the TextView. It will give you a cursor pointing to the selected position as a parameter.

Hope this helps.

+1
source

If you still have an instance of this class, you should be able to search in the array that you used in the adapter to collect the necessary information.

0
source

Source: https://habr.com/ru/post/1306778/


All Articles