android - AsyncTask slow with OnClick -
goodmorning, have button on android app launches search on web (through google endpoints) through asynctask. problem button not "unclick" until asynctask completed, may take several seconds. when internet connection slow, makes application crash, in case application stuck until asynctask completed. reason using asynctask eliminate problem, don't happens!
here onclicklistener:
searchlistener = new onclicklistener() { @override public void onclick(view v) { string cname=textcourse.gettext().tostring(); if (!cname.isempty()){ try { collectionresponsewine listavini= new querywinestask(messageendpoint,cname,5).execute().get(); } catch (interruptedexception e) { showdialog("errore ricerca"); e.printstacktrace(); } catch (executionexception e) { showdialog("errore ricerca"); e.printstacktrace(); } } else{ showdialog("inserisci un piatto"); } } };
and here asynctask being called:
private class querywinestask extends asynctask<void, void, collectionresponsewine> { exception exceptionthrown = null; messageendpoint messageendpoint; string cname; integer limit; public querywinestask(messageendpoint messageendpoint, string cname, integer limit) { this.messageendpoint = messageendpoint; this.cname=cname; this.limit=limit; } @override protected collectionresponsewine doinbackground(void... params) { try { collectionresponsewine wines = messageendpoint.listwines().setcoursename(cname).setlimit(limit).execute(); return wines; } catch (ioexception e) { exceptionthrown = e; return null; //handle exception in postexecute } } protected void onpostexecute(collectionresponsewine wines) { // check if exception thrown if (exceptionthrown != null) { log.e(registeractivity.class.getname(), "exception when listing messages", exceptionthrown); showdialog("non ci sono vini associati al tuo piatto. aggiungine uno!"); } else { messageview.settext("vini piu' votati per " + cname + ":\n\n"); for(wine wine : wines.getitems()) { messageview.append(wine.getname() + " (" + wine.getscore() + ")\n"); } } } }
...execute().get()
blocking. makes ui thread wait task complete.
don't get()
. use onpostexecute()
result (wines
) of task , update ui.
Comments
Post a Comment