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.

How to clone an object in JavaScript

In JavaScript the assignation of the objects always is through references, for example:

var ob1 = {a:'hi'};

var ob2 = ob1;

If you print this, It show the following:

console.log(ob1);

console.log(ob2);

{ a: 'hi' }

{ a: 'hi' }

What happend if you modify ob2? For example:

ob2.a = 'hi ob2';

Now I’ll print the value of both of them

console.log(ob1);

console.log(ob2);

The result is:

{ a: 'hi ob2' }

{ a: 'hi ob2' }

The value of both is the same, because the value of ob2 is the reference to ob1,  then how we can have two objects diferents, or exactly how to clone an object?.

That is very simple, you just need convert this object to string and convert it to object again.

var ob1 = {a:'hi'};

var ob2 = JSON.parse(JSON.stringify(ob1));

With this, now you have differents objects, if you modify ob2, this change does not affect to object ob1.

Very simple.