2014-01-14 24 views
0

我在項目點擊AutoCompleteTextView時遇到了麻煩。用我的代碼下面,我沒有得到點擊項目的ID在SQLite數據庫中。假設我點擊了自動完成下拉菜單中顯示的第二項。我從ID號爲2的數據庫中獲取值,而不是數據庫中ID爲不同的選定項的值。我確信我的onItemClick實現是錯誤的。我希望somone能幫我弄明白。很長時間以來,我一直在爲此感到煩惱。OnItemClick到AutoCompleteTextView

我的代碼:

SearchTrainee = (AutoCompleteTextView) findViewById(R.id.search); 

    trainees = new ArrayList<HashMap<String, String>>(); 
    trainees = DatabaseHelper.getInstance().getStoredTrainees(); 

    String str[] = new String[trainees.size()]; 
    for (int i = 0; i < trainees.size(); i++) { 
     str[i] = trainees.get(i).get("display"); 
    } 

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
      R.layout.search_autocomplete, str); 
    SearchTrainee.setAdapter(adapter); 
    SearchTrainee.setOnItemClickListener(this); 
} 

@Override 
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 


     System.out.println("Last name: " + trainees.get(arg2).get("last_name")); 
     //currentTrainee.setFirstname(trainees.get(arg2).get("first_name")); 
     // currentTrainee.setCompany(trainees.get(arg2).get("company")); 
     // System.out.println(currentTrainee.getFirstname()); 


} 
+0

不使用ArrayAdapter,使用SimpleCursorAdapter代替 – pskink

+0

@pskink任何具體的原因花花公子? – bShah

+0

,因爲如你注意到你丟失物品ID – pskink

回答

0

的問題是自動完成的視圖將過濾顯示的內容,使之不匹配你的初始數組,這意味着你不能依賴onItemClick中給出的索引來搜索trainee數組。

要限制的變化量在你的代碼,這裏是你可以做什麼:

使用SimpleAdapter像這樣:

SimpleAdapter adapter = new SimpleAdapter(this, trainee, 
     R.layout.search_autocomplete, new String[] {"display"}, 
     new int[] {R.id.text}); 
// R.id.text is to be replaced by the id of your TextView in the search_autocomplete layout 

然後,在onItemClick,檢索代表學員地圖像這樣:

Map<String, String> selectedTrainee = ((Map<String, String>) arg0.getItemAtPosition(arg2)); 

然後,您可以操縱對象,你需要的任何方式(姓selectedTrainee.get("last_name")

+0

我儘量按你的說法:) – bShah

+0

你真棒。它的作用像魅力。在這種情況下,我也有其他問題。由於我的解決方案,我設法也是唯一的。非常感謝你。祝你今天愉快!! – bShah

1

我想你的意思是最後一行是這樣的代碼:

System.out.println("Last name: " + arg0.getItemAtPosition(arg2).get("last_name")); 
+0

不是真的。沒有提到缺少轉換,適配器僅包含字符串,而不包含完整的映射。 – njzk2

+0

@ user3193470 .get(「last_name」)不可能實現。對不起 – bShah

+0

你是對的@ njzk2。 – bShah