java - android.os.NetworkOnMainThreadException even on using AsynTask -
this question has answer here:
i trying consume rest webservice. can not perform network operations in ui thread tried doing using asynctask. below code asynctask
public class callmeserviceasynctask extends asynctask<string, void, list<service>> { @override protected list<service> doinbackground(string... params) { callmeservice service= servicefactory.getcallmeservice(); list<service> services= service.getallservices(); //calls web service , parses json response return services; } }
callmeservice.getallservice() provides service layer calls below method
public static string makerestrequest(string url) throws malformedurlexception,ioexception { string response=""; url resturl= new url(url); httpurlconnection connection=(httpurlconnection)resturl.openconnection(); inputstream is=new bufferedinputstream(connection.getinputstream()); response=convertstreamtostring(is); return response; }
now calling task oncreate method of activity below
protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); strictmode.threadpolicy policy = new strictmode.threadpolicy.builder().permitall().build(); strictmode.setthreadpolicy(policy); setcontentview(r.layout.activity_home); this.optionslist=(listview)findviewbyid(r.id.optionslist); //string[] options={"teacher","plumber","electricians"}; arrayadapter adapter=getservicemenu(); this.optionslist.setadapter(adapter); optionslist.setonitemclicklistener(this); } private arrayadapter getservicemenu() { arrayadapter adapter= null; try { list<service> menuservices= new callmeserviceasynctask().execute("").get(); adapter = new arrayadapter(this, android.r.layout.simple_list_item_1, menuservices); } catch(exception x) { x.printstacktrace(); } return adapter; }
i new android development , not able figure out issue above code. please me out. let me know if need more code understand.
get rid of get()
call @ end of:
new callmeserviceasynctask().execute("").get();
that blocking main application thread.
instead, set arrayadapter
in onpostexecute()
of asynctask
.
or, use ordinary thread instead of asynctask
, , use event bus deliver web service results ui layer, demonstrate in this sample app.
or, use library offering newer http api, okhttp, makes asynchronous http operations easier, demonstrate in this sample app.
or, switch library retrofit, makes asynchronous rest web service calls easier, demonstrate in this sample app.
Comments
Post a Comment