Issue
I am trying to make a simple app. Where user sees one edittext .. enters some text in it.. and then press send... then the server on laptop receives that message.
Now the NetworkOnMainThread exception is giving me Headaches......the app works perfectly for 2.3.3 because there was no such thing as NetworkOnMainThread Exception that time.
Having searched a lot .. Two solutions are
- Making new thread for networking OR
- AsyncTask.
I tried both without any results.
Try 1: With Separate Thread:
Now what I could understand is that I had to start a separate thread. Ok. I did.
Following is my client side code.
EditText e ;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e= (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.textView1);
Thread startNetworking = new Thread(new NetworkThread());
startNetworking.start();
}
public void sendMessage(View v){
if(NetworkThread.sendToClient(e.getText().toString()))
tv.setText("Status : Successful");
else
tv.setText("Status : Unsuccessful");
}
sendMessage is onClick function for my send button. I have another JAVA file NetworkThread.java....
Here is a code for that :
public class NetworkThread implements Runnable{
static DatagramSocket socket;
static InetAddress add;
public void run() {
try {
socket = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
add = InetAddress.getByName("192.168.1.12");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean sendToClient(String message){
DatagramPacket p = new DatagramPacket(message.getBytes(),message.getBytes().length,add,4444);
try {
socket.send(p);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
This is still doesn't work. I first want to exhaust this first try then I will move onto asking here about AsyncTask and what I have tried. So for time being please help me achieve this simple task of sending and receiving a string.
Solution
Unfortunately, having sendToClient()
defined in the same class as NetworkThread
doesn't mean that it will run on your network-specific thread. The sendToClient()
method will still run on your main (UI) thread because it's being called from your onClick()
method. UI callbacks, such as onClick()
, are always processed on the UI thread.
I would recommend using an AsyncTask
as it enables you to send arbitrary data (such as your message
parameter) to the background/network thread before it executes. Continuing to use Runnable
and Thread
will require extra machinery to synchronize the execution of your UI and network threads, and these challenges are handled behind the scenes by AsyncTask
.
Answered By - acj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.