android - Calling an AsyncTask twice behavior -
i trying implement search bar automatically searches type.
my idea have asynctask
fetches search data server, can't figure how asynctask
behave use of it.
let's have searchasynctask
.
every time text field edited call
new searchasynctask().execute(params);
so here's question: behavior of be? starting many different threads return , call onpostexecute()
? or first task called stopped mid-task if instance called while it's still working? or totally different?
what if write way?
searchasynctask = new searchasynctask().execute(params); ... a.execute(params2); a.execute(params3); ...
i have implemented app's search function in same way. use textwatcher
build search results , when user types. keep reference of asynctask achieve this. asynctask declaration:
searchtask mysearchtask = null; // declared @ base level of activity
then, in textwatcher
, on each character input, following:
// s.tostring() user input if (s != null && !s.tostring().equals("")) { // user has input characters // check if asynctask has not been initialised yet if (mysearchtask == null) { mysearchtask = new searchtask(s.tostring()); } else { // asynctask either running or has finished, try cancel in case mysearchtask.cancel(true); // prepare new asynctask updated input mysearchtask = new searchtask(s.tostring()); } // execute asynctask mysearchtask.execute(); } else { // user has deleted search string // search box has empty string "" if (mysearchtask != null) { // cancel asynctask mysearchtask.cancel(true); } // clean // clear results list sresultslist.clear(); // update ui sresultadapter.notifydatasetchanged(); }
Comments
Post a Comment