RegedUser00x
RegedUser00x

Reputation: 2383

Doing networking in Android from AsyncTask gives NetworkOnMainThreadException

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?

Upvotes: 0

Views: 1671

Answers (2)

D-Dᴙum
D-Dᴙum

Reputation: 7890

Your onPostExecute() of Messager class is done on the Main thread. You are also doing network IO with

InetAddress.getByName("130.237.161.23");

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234847

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.

Upvotes: 1

Related Questions