rsd_unleashed
rsd_unleashed

Reputation: 161

Android AutoCompleteTextView : Perform a AsyncTask call only once on TextChange

I have an AutoCompleteTextView in my layout. After the user entered the first character, I'd like to do an API call, which I'm doing in an AsyncTask. I've used addTextChangedListener and I'm doing the API call on TextChanged. But the problem is that the API call is getting done each time the user makes any change to the AutoCompleteTextView.

But I'd want the API call to happen only once, that is after the first character is inputted. How do I achieve this ?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_places_search);
    search_airport = (AutoCompleteTextView) findViewById(R.id.place_search);
    autocompleteadapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, airports);
    search_airport.setAdapter(autocompleteadapter);
    search_airport.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mAirport = new AsyncTaskAirport(search_airport.getEditableText().toString().substring(0, 1));
            mAirport.execute((Void) null);

        }

        @Override
        public void afterTextChanged(Editable s) {


        }
    });


}

Upvotes: 0

Views: 596

Answers (2)

Kirtan
Kirtan

Reputation: 1812

You can solve your problem with a timer.Here is how

@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
    int COMPLETION_DELAY = 2000;
    if (timer != null)
    {
        timer.cancel();
        timer.purge();
        timer = null;
    }
    timer = new Timer();
    timer.schedule(new TimerTask()
    {
        @Override
        public void run()
        {
            new Handler(Looper.getMainLooper()).post(new Runnable()
            {
                @Override
                public void run()
                {
                    if (s.toString().length() >= appCompatAutoCompleteTextView.getThreshold())
                    {
                         //CALL WebService Here
                    }
                }
            });
        }
    }, COMPLETION_DELAY);
}

now your service will not be called when user making changes while typing in auto complete. service will only be called once user stops + 2 Second.

Upvotes: 0

Pradeep Gupta
Pradeep Gupta

Reputation: 1770

try this,

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if(s.toString().trim().length()==1){
       mAirport = new AsyncTaskAirport(search_airport.getEditableText().toString().substring(0, 1));
       mAirport.execute((Void) null);
     }

 }

Upvotes: 1

Related Questions