我創建了一個顯示所有聯繫人姓名的AutoCompleteTextView框,但在查看Android API後,似乎我的方法可能效率很低。Android - 自動填充聯繫人
當前我抓住所有聯繫人的光標,將每個姓名和每個聯繫人ID放入兩個不同的數組,然後將名稱數組傳遞給AutoCompleteTextView。當用戶選擇一個項目時,我查找在上面創建的第二個id數組中選擇的聯繫人的ID。下面的代碼:
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;
}
必須有這樣做的更好的方式 - 基本上我掙扎,看我怎麼能找到一個用戶在AutoCompleteTextView選擇哪個項目。有任何想法嗎?
乾杯。
乾杯,我想我的問題是多一次的名稱已被選中,反正是有告訴,如果它是在自動完成列表,或者我必須重新查詢聯繫人數據庫表中寫入名稱的匹配。我發現答案是後者。 感謝您向正確的方向推動 – 2010-04-16 08:28:31