Issue
I am trying to code a simple chat app for Android so I have a chat server and I am trying to connect to it. So in the main class I have
final EditText etHost = (EditText) findViewById(R.id.entry1);
final EditText etPort = (EditText) findViewById(R.id.entry2);
final EditText messageBoard = (EditText) findViewById(R.id.editText1);
final EditText etSend = (EditText) findViewById(R.id.editText2);
soEd = new SocketAndEditText(etHost, etPort, messageBoard, etSend);
SetNetworking net = new SetNetworking();
SocketAndEditText net.execute(soEd);
final Button sendButton = (Button) findViewById(R.id.button2);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Messager mes = new Messager();
mes.execute(soEd);
}
});
SocketAndEditText
is a class where I simply keep the socket and four EditText
components. The idea is that SetNetworking
will establish the network connection and Messager
will be sending messages. Both classes implement AsyncTask
:
public class SetNetworking extends AsyncTask<SocketAndEditText, Void, Void> {
...
public class Messager extends AsyncTask<SocketAndEditText, Void, Void> {
...
But strangely in onPostExecute(Void result)
in Messager
when I try to do even a quite simple thing as
try {
InetAddress address1 = InetAddress.getByName("130.237.161.23");
boolean reachable = address1.isReachable(4456);
messageBoard.setText("Is host reachable?" + reachable);
} catch (Exception e) {
messageBoard.setText("Test not working! " + e.toString());
}
I get this:
Test not working! android.os.NetworkOnMainThreadException
Why since it is in the AsyncTask and not in the main thread?
Solution
You cannot do network I/O in onPostExecute
of an AsyncTask
, since that method runs on the UI thread. You need to do all network activity in doInBackground
.
Answered By - Ted Hopp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.