android - What is the relationship between AsyncTask and Activity? -
i have been given assignment develop application send server request , response , using json parsing, display data content listview.
i don't understand asynctask , how integrate classes. hope accommodate. regards
what should do?
the first, send request server second, response thirds, parse data inputstream got response fourth, show on listview oh, done. right now, first step.
how send request server?
you can use httpurlconnection or httpclient
so, what's problem when send request server?
i think know when send request server, problem: network bad, inputstream server large, ...
and how resolve?
with single statement, can't take along time do. task takes along time do, have handle in other thread. that's reason why should use thread or asynctask.
what's asynctask?
you can read more search on google. tell you: how use asynctask solve spec.
what asynctask do?
when create instance of asynctask,
it's follow:
-> create -> preexecute -> execute (doinbackground) - postexecute
ok.
right now, answer question:
create object extends asynctask.
public class downloadfile extends asynctask<string, void, inputstream> { @override public void onpreexecute() { // can implement method if want prepare before start execute (send request server) // example, can show dialog, or something,... } @override public inputstream doinbackground(string... strings) { // important method in asynctask. have implements method. // demo: using httpclient inputstream minputstream = null; try { string uri = strings[0]; httpclient mclient = new defaulthttpclient(); httpget mget = new httpget(uri); httpresponse mresponse = mclient.execute(mget); // there 2 methods: getstatuscode & getcontent. // dont' remember they. can find in httpresponse document. minputstream = mreponse.getentity().getcontent(); } catch (exception e) { log.e("tag", "error: " + e.getmessage()); } return minputstream; } @override public void onpostexecute(inputstream result) { //after doinbackground, method invoked if implemented. // can result result. } } ok. have use class
in mainactivity or want invoke class, create instance of class
downloadfile mdownloader = new downloadfile(); mdownloader.execute("your_url"); using method mdownloader.get(); inputstream if want get. have surround try-catch
i know, if want use dialog, search on google how show dialog while download file server.
and suggest you should remember, nead runonuithread if want update ui. because asynctask thread. can not update ui if in thread not mainthread.
Comments
Post a Comment