multithreading - How to use Android network access, threads and handlers -


trying write first android application, , starting point have application read text file website, , display in application.

i've given application network access, , found network access cannot made main thread, found separate threads can't make changes textviews. tried implement handler, , fell apart.

i used global variable triggered button instead main thread update textview, when added timer mix run same thread, textview coming blank or crashing.

could outline recommended steps/code this, i'm struggling put components me started?

update: working code put together:

private class getupdate extends asynctask<string, void, string> {     @override     protected string doinbackground(string... params){         try {             url urlobj = new url("https://webpage.com");             httpsurlconnection urlconnection = (httpsurlconnection) urlobj.openconnection();             urlconnection.setconnecttimeout(5000);             inputstream = urlconnection.getinputstream();             bufferedreader br = new bufferedreader(new inputstreamreader(is, "utf-8"));              string temp = br.readline();             updateinfo = updateinfo + br.readline();         }         catch (java.net.sockettimeoutexception e) {             updateinfo = updateinfo + "no network";         }         catch (ioexception e){             updateinfo = updateinfo + "failed";             throw new runtimeexception(e);         }         return "";     }      protected void onpostexecute(string result) {         textview statustext = (textview) findviewbyid(r.id.statustext);         statustext.settext(updateinfo);     }      @override     protected void onpreexecute() {         simpledateformat sdf = new simpledateformat("dd/mm/yyyy hh:mm:ss");         string currentdateandtime = sdf.format(new date());         updateinfo = "status -\n\r" + currentdateandtime + " - ";     }      @override     protected void onprogressupdate(void... values) {}     } 

and timer located within oncreate:

    timer mytimer = new timer();     mytimer.schedule(new timertask() {         @override         public void run() {             new getupdate().execute("");         }     }, 0, 5000); 

here example:-

on oncreate method

txtmessage = (textview) findviewbyid(r.id.txt_push_message); 

new task().execute();

 class task extends asynctask<string, string,string>{      @override     protected void onpostexecute(string s) {         super.onpostexecute(s);         txtmessage.settext("hi there");     }      @override     protected string doinbackground(string... params) {          //do related data , return         //return proper value         return null;     } } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -