I am having making my edittext field autocomplete for contacts phone numbers. I know how to get contacts from database and display them in text field but i need them to autocomplete just incase the user wants to type a name into textfield. I understand how to get an array to auto complete and the whole theory behind that. But how to pull from phone contacts is difficult. I’ve seen many tutorials and also various question on stack overflow, but still kind of stumped. A code snippit would help please.
public class MyContacts extends Activity {
AutoCompleteTextView txtPhoneNo;
public ArrayList<String> c_Name = new ArrayList<String>();
public ArrayList<String> c_Number = new ArrayList<String>();
String[] name_Val = null;
String[] phone_Val = null;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
txtPhoneNo = (AutoCompleteTextView) findViewById(R.id.txtPhoneNo);
}
Uri contacts = Uri.parse("content://icc/adn");
ContentResolver cr = getContentResolver();
Cursor managedCursor1 = cr.query(contacts, null, null, null, null);
{
if (managedCursor1.moveToFirst()) {
String contactname;
String cphoneNumber;
int nameColumn = managedCursor1.getColumnIndex("name");
int phoneColumn = managedCursor1.getColumnIndex("number");
Log.d("int Name", Integer.toString(nameColumn));
Log.d("int Number", Integer.toString(phoneColumn));
do {
// Get the field values
contactname = managedCursor1.getString(nameColumn);
cphoneNumber = managedCursor1.getString(phoneColumn);
if ((contactname != " " || contactname != null)
&& (cphoneNumber != " " || cphoneNumber != null)) {
c_Name.add(contactname);
c_Number.add(cphoneNumber);
}
} while (managedCursor1.moveToNext());
}
name_Val = (String[]) c_Name.toArray(new String[c_Name.size()]);
phone_Val = (String[]) c_Number.toArray(new String[c_Name.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, name_Val);
txtPhoneNo.setAdapter(adapter);
}
}
My code… no compile errors but still does not work
Better would be to fetch the Contacts and store it in
ArrayList. Then you can just bind the ArrayList with theAutoCompleteTextView. Then the rest of the part is just easy to filter the ArrayList when you the user types in theAutoCompleteTextView.UPDATE
You can create a POJO Class with getter-setter of
contact_nameandcontact_number. Then createList<POJO> list = new ArrayList<POJO>();. Then just add the contact_name and contact_number to thelistusingPOJOclassAnd finally set this
listto theAdapter.And then in the Adapter class you can set it to the TextView using