java - android.os.NetworkOnMainThreadException how to adapt this code that it runs in a seperate thread -
i'm developing software pc , mobile talking server. when run code java desktop app gives me following error android.os.networkonmainthreadexception
i tried implement class thread think did not right. still gives me error
i glad support.
the class serveraccessmobile doing networking , has 2 public methods, 1 getting data server , 1 setting data on server
and how want execute activity / service
serveraccessmobile serveraccessmobile = new serveraccessmobile(); arraylist <string> datafromserver = **serveraccessmobile.getdatafromserver()**; arraylist <string> datatosend = ..... **serveraccessmobile.setdataoserver(datatosend)**; this code class serveraccessmobile
public class serveraccessmobile { // private variables private objectoutputstream outputstream; private objectinputstream inputstream; ... // constructor public serveraccessmobile(string arg1) { ... } **private arraylist<string> run(arraylist<string> messagetosendlist)** { arraylist <string> receivedmessagelist = new arraylist <string> (); try // connect server, streams, process connection { connecttoserver(); // create socket make connection getstreams(); // input , output streams senddata(messagetosendlist); receivedmessagelist = processconnection(); } catch ( eofexception eofexception ) { system.out.println("\n terminated connection"); } catch ( ioexception ioexception ) { ioexception.printstacktrace(); } { closeconnection(); // close connection } return receivedmessagelist; } public arraylist <string > getdatafromserver(){ arraylist< string > commandmessage = new arraylist< string > (); commandmessage.add("getdata"); arraylist< string > receivedmessagelist = new arraylist< string > (); // start server communication receivedmessagelist = **run(commandmessage);** } public void setdataonserver(arraylist <string> messagetosendlist){ // start server communication **run(messagetosendlist);** } } now question,
the code within run() method should run in seperate thread, not ui thread how implement correct?
thank u
you can find detailed description threads @ following link: http://developer.android.com/guide/components/processes-and-threads.html#threads
you this
new thread(new runnable() { public void run() { serveraccessmobile serveraccessmobile = new serveraccessmobile(); arraylist <string> datafromserver = **serveraccessmobile.getdatafromserver()**; arraylist <string> datatosend = ..... serveraccessmobile.setdataoserver(datatosend); } }).start(); if want update ui thread you'd have call view.post(runnable) method.
Comments
Post a Comment