philgiese
philgiese

Reputation: 651

How to implement the javascript setTimeout function in Java

I am currently trying to integrate a live search functionality in android. I use a customized Autocomplete widget. The widget itself provides me with a threshold to only start a query after a certain amount of characters have been typed in. But what I also want is that a query only starts, say if a user has stopped typing for 2 seconds.

As I load my contents with a AsyncTask I tried blocking the doInBackground function by calling Thread.sleep() right at the beginning. If the user would then continue typing the program would look after an existing task, cancel it and start a new one. This was my idea. But it doesn't quite work the way I expected. Sometimes it sends out queries even if the user is still typing, sometimes queries are canceled after the users stopped typing.

Do you have any ideas on this or maybe a better way to solve this?

Here are the code snippets:

1. The function that is called on text changes:

public void afterTextChanged(Editable s) {
    if(mWidget.enoughToFilter()) {
        if(mTask != null && mTask.getStatus() != Status.FINISHED) {
            mTask.cancel(true);
        }

        mTask = new KeywordSearchLoader(mActivity, 
                mItems);

        mTask.execute(s.toString());

    }
}

2. doInBrackground

try {
    Thread.sleep(Properties.ASYNC_SEARCH_DELAY);
} catch (InterruptedException e) {
    Log.e(TAG, "the process was interrupted while sleeping");
    Log.w(TAG, e);
}

Thanks Phil

Upvotes: 0

Views: 2581

Answers (1)

Peter Knego
Peter Knego

Reputation: 80340

Create a Handler and use .postDelayed(..) to run a background task after some delay.

If user presses the key then call handler.removeCallback(..) and then again .postDelayed(..) to add a new delayed callback.

Upvotes: 2

Related Questions