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) {
}
});
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
Gratitude to Stefan Richter! I would like to add that it is possible to use List<T>
directly when you construct the adapter:
AutoCompleteTextView autoCompleteTextView = dialogView.findViewById(R.id.autoComplete);
// Where mStudentsInfo is List<StudentInfo>
ArrayAdapter<StudentInfo> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, mStudentsInfo);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object item = parent.getItemAtPosition(position);
if (item instanceof StudentInfo) {
StudentInfo studentInfo = (StudentInfo) item;
// do something with the studentInfo object
}
}
});
And also do not forget to override the toString()
method in StudentInfo.class
:
public class StudentInfo {
....
@Override
public String toString() {
return studentName;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With