android - "realtime" search using AsyncTask? -


i writing application searches database in "realtime". i.e. user presses letters updates search results list.

since search can take while, need search in background , allow new key presses re-start search. user presses 'a' (and code starts searching "a"), presses 'b' - code not wait "a" search end, start searching "ab", rather stop "a" search, , start new "ab" search.

  • to decided search in asynctask. wise decision ?

now - whenever keypress detected, test see if have asynctask running. if - signal (using boolean within asynctask) should stop. set timer re-test asynctask within 10 msec, see if terminated, , start new search.

  • is smart method ? or there approach take ?

tia

first yes, asynctask way this. problem see approach timer waiting watch die. when invoke asynctask hold onto reference of it. let keep state know if it's out searching or it's has returned. when user clicks letter can tell asynctask cancel. this:

public void onclick() {    if( searchtask != null ) {       searchtask.cancel();    }     searchtask = new searchtask( myactivity.this ).execute( textinput.gettext() ); }  public class searchtask extends asynctask<string,integer,list<searchresult>> {     private boolean canceled = false;      protected onpostexecute( list<searchresult> results ) {        if( !canceled ) {           activity.handleresults( results );        }     }      public void cancel() {        canceled = true;     } } 

this safe because onpostexecute() on ui thread. , cancel() called ui thread there no thread safety issues, , no need synchronize. don't have watch thread die. let gc handle cleaning up. once drop reference asynctask cleaned up. if asynctask blocks that's ok because hangs background thread, , when timeout hits resume calling onpostexecute(). keeps resources minimum without using timer.

things consider approach. sending new request everytime new letter typed can overload servers because first few letters going produce largest search results. either limit number of results you'll return server (say 10-50 results max), or wait until they've entered enough characters keep results down (say 3). cons of making user type more characters feedback doesn't kick in until 3 chars. however, pro dramatically reduce hits on server.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -