Question

I am having a trouble on Item click to the the AutoCompleteTextView. With my code below, I am not getting the id of clicked item as in SQLite database. Suppose I click the 2nd item that is shown in the AutoComplete drop down. I get the value from the database that is in the id no.2, instead of the value of selected item whose id in database is different. I am sure my implementation onItemClick is wrong. I hope somone will help me to figure it out. I am troubling with this since long time.

My Code:

  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());


}
Was it helpful?

Solution 2

The problem is that the autocomplete view will filter the displayed content, making it not matching your initial array, meaning you cannot rely on the index given in onItemClick to search the trainee array.

To limit the amount of change in your code, here is what you can do:

Use a SimpleAdapter like so:

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

Then, in onItemClick, retrieve the Map that represent the trainee like so:

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

You can then manipulate the object any way you need (last name is selectedTrainee.get("last_name"))

OTHER TIPS

I think you meant to code the last line as this:

System.out.println("Last name: " + arg0.getItemAtPosition(arg2).get("last_name"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top