How to populate data in a AutoCompleteTextView from database or from anywhere

This post belongs to a series of publications that I will write with the intent of the learn about the development Android, I’m a backend developer but the system android called my attention.

Sometime we need populate a AutoCompleteTextView but with the data from database or other repository of data, this depending if the user write for example: apple, app, appstore or play, playground, playstore, etc.

Then, how fill these record depending of the what he write the user? The class

AutoCompleteTextView has a method called addTextChangedListener this method receive the interface TextWatcher.

The interface TextWatcher needs implements three methods like the following:

@Override
public void beforeTextChanged(CharSequence sequence, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence sequence, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable s) {

}

In this post I will use the method onTextChanged, this method receive four values, today the value interest is sequence, this value has the text that the user wrote.

On the method onTextChanged you just need create a logic for get records from databa or request api for example and create something similar to this:

//Simulate search from database or other repository
//and here create an array with the records obtained
String [] items2 = new String[]{"Apple","App","AppStore"};

//now recreate the ArrayAdapter with the new Array String and set this to variable of the AutoCompleteTextView
adapter = new ArrayAdapter<>(self,android.R.layout.simple_expandable_list_item_1,items2);
autoCompleteTextView.setAdapter(adapter)

This works for me and is very easy, I don’t know well if this is the better option or if exists some better way and with the better performance.

If you want you can clone the sample project from github.

Leave a Reply