How to Effective Search On Edittext : Delay EditTexts’s ChangedTextEvent

April 18, 2018 0 Comments

Hello Friends,

Search on through Api, it's time consuming,

Solve the Problem: Delay EditTexts’s ChangedTextEvent


During auto-complete, you expect the results to get filtered with every key stroke. In contrast you want a search get triggered once you finished typing. In case the user didn’t finish typing his keywords, we’d execute a search request with every key typed.

To avoid that many requests and optimize search experience, you can use a TextWatcher for the search field (EditText). The TextWatcher requires you to implement three methods:

  • beforeTextChanged: perform operations before the text in EditText changes

  • afterTextChanged: perform operations after the text in EditText changes

  • onTextChanged: perform operations while the text in EditText changes


private EditText searchText;  
private TextView resultText;
private Timer timer;

private TextWatcher searchTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// user typed: start the timer
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// call your API Here,
}
}, 600); // 600ms delay before the timer executes the „run“ method from TimerTask
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// nothing to do here
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// user is typing: reset already started timer (if existing)
if (timer != null) {
timer.cancel();
}
}
};

 

Contributer

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google

0 comments:

Popular Posts