Selected Item of Autocomplete Textview Show as simple Textview?

bhoot4242 picture bhoot4242 · Apr 5, 2013 · Viewed 52.3k times · Source

I am using an Autocomplete Textview which shows some names from database.I want to show a name in a textview which I selected from autocomplete textview.Here is my code:

ArrayList<String> s1 = new ArrayList<String>();

      for (StudentInfo cn : studentInfo) {
            s1.add(cn.getName());
        }
        ArrayAdapter<String> adapter =  new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,s1); 
       a1.setThreshold(1); 
        a1.setAdapter(adapter);

a1.setOnItemClickListener(new OnItemClickListener() {

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

Answer

Stephan Richter picture Stephan Richter · Oct 1, 2015

Try it this way:

AutoCompleteTextView a1 = (AutoCompleteTextView) findViewById(...);

StudentInfo[] s1 = studentInfo.toArray(new StudentInfo[studentInfo.size()]);

ArrayAdapter<StudentInfo> adapter = new ArrayAdapter<StudentInfo>(this, android.R.layout.simple_dropdown_item_1line, s1);
a1.setAdapter(adapter);
a1.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
        Object item = parent.getItemAtPosition(position);
        if (item instanceof StudentInfo){
        StudentInfo student=(StudentInfo) item;
            doSomethingWith(student);
        }
    }
});

The ArrayAdapter uses the toString() method of StudentInfo to generate the displayed texts, so you need to implement a nice toString method.

This way, this kind of implementation can be adapted to any object type.

Btw.: i prefer android.R.layout.simple_spinner_dropdown_item instead of android.R.layout.simple_dropdown_item_1line