Aim :
I want to get some strings from webservice and populate AutoCompleteTextView with them.This is simple but what I want actually is to begin search (invoke webservice) when typing finished.
I mean, for example, I type something and 3 seconds after typing finished, AutoCompleteTextView would get populated and suggestions show up.
What I did so far :
As you can see in the code below, I used a CountDownTimer to achieve this. I set it 3 seconds and start it in OnTextChanged. When user type, I clear CountDownTimer and create a new instance of it and start it again.
So, whenever user type -on every key press- I reset counter.
After that, I call my method - which invoke webservice and populate AutoCompleteTextView - in CountDownTimer's OnFinish().
Problem :
When I finish typing, everything works as expected as I can see in debug mode. But suggestions doesn't come up FOR ONLY FIRST SEARCH.
I mean, it works as well but AutoCompleteTextView doesn't get populated with data for only FIRST TIME.
Note :
I invoke webservice both synchronous and asynchronous way.
counter=new MyCount(3000, 1000);
autoComplete.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable editable) {
if(isBackPressed){ //catch from KeyListener, if backspace is pressed don't invoke web service
isBackPressed=false;
return;
}
String newText = editable.toString();
searchText=newText;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(isBackPressed){
isBackPressed=false;
return;
}
counter.cancel();
counter=new MyCount(3000, 1000);
counter.start();
}
});
Here is my CountDownTimer Class
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
invoke_webservice(searchText);
}
@Override
public void onTick(long millisUntilFinished) {
}
}
Here is my method to invoke webservice in synchronous way
public void invoke_webservice(String key){
try{
. //code to invoke webservice and populate string [] results
.
.
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,results);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
Here is my method to invoke webservice in asynchronous way
class getJson extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... key) {
String newText = key[0];
. //code to invoke webservice and populate string [] results
.
.
runOnUiThread(new Runnable(){
public void run(){
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,results);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
return null;
}
}
Thanks in advance