-4

I'm getting NetworkOnMainThreadException while using Runnable

Code:

public class FullscreenActivity extends AppCompatActivity {
    public Socket socket;
    public int SERVERPORT = 5000;           /* port 5000 (for testing) */
    public String SERVER_IP = "10.0.2.2";   /* local Android address of localhost */
    ViewFlipper flipper;
    ListView listing;

    public void attemptConnect(View view) {
        try {
            EditText editTextAddress = (EditText) findViewById(R.id.address);
            EditText editTextPort = (EditText) findViewById(R.id.port);
            String SERVER_IP_loc = editTextAddress.getText().toString();
            int SERVERPORT_loc = Integer.parseInt(editTextPort.getText().toString());
            System.out.println("Attempt Connect: IP " + SERVER_IP_loc + " Port: " + SERVERPORT_loc);
            System.out.println("SET");
            ClientThread myClientTask = new ClientThread(SERVER_IP_loc, SERVERPORT_loc);
            myClientTask.run();
            System.out.println("CONNECTED");
            flipper.setDisplayedChild(1);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    // Thinks the following is not a thread ??
    class ClientThread implements Runnable {
        ClientThread(String addr, int port) {
            SERVER_IP = addr;
            SERVERPORT = port;
        }

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                // gets to this line fine
                socket = new Socket(serverAddr, SERVERPORT); 
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
}

My permissions are set up to allow internet access:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

I'm getting the following error:

    6188-6188/test W/System.err: android.os.NetworkOnMainThreadException
6188-6188/test W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
6188-6188/test W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
6188-6188/test W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
6188-6188/test W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
6188-6188/test W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
6188-6188/test W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
6188-6188/test W/System.err:     at java.net.Socket.startupSocket(Socket.java:592)
6188-6188/test W/System.err:     at java.net.Socket.<init>(Socket.java:226)
6188-6188/test W/System.err:     at test.FullscreenActivity$ClientThread.run(FullscreenActivity.java:363)
6188-6188/test W/System.err:     at test(FullscreenActivity.java:340)
6188-6188/test W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
6188-6188/test W/System.err:     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(test:270)
6188-6188/test W/System.err:     at android.view.View.performClick(View.java:5198)
6188-6188/test W/System.err:     at android.view.View$PerformClick.run(View.java:21147)
6188-6188/test W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
6188-6188/test W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
6188-6188/test W/System.err:     at android.os.Looper.loop(Looper.java:148)
6188-6188/test W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
6188-6188/test W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
6188-6188/test W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
6188-6188/test W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

As far as I can tell, this should function as expected. It seems to think the Runnable isn't a thread, but I can't figure out why.

interplex
  • 277
  • 1
  • 2
  • 8

1 Answers1

2

You need a Thread to run your Runnable for you. Simply calling run on a Runnable does not run it on a different thread.

new Thread(new ClientThread(SERVER_IP_loc, SERVERPORT_loc)).start();
George Mulligan
  • 11,813
  • 6
  • 37
  • 50
  • This doesn't actually solve the problem. It still throws the exception when trying to make the new socket. – interplex Jan 24 '16 at 22:25
  • Are you sure it's when creating the socket? Are you trying to read from the `Socket` off the UI thread too? – George Mulligan Jan 24 '16 at 22:27
  • Yes. This: `InetAddress serverAddr = InetAddress.getByName(SERVER_IP); System.out.println("RUN2"); socket = new Socket(serverAddr, SERVERPORT); System.out.println("RUN3");` makes it to RUN2 but not to RUN3. – interplex Jan 24 '16 at 22:29
  • Sorry I meant to have you call `new Thread(...).start()` instead of `new Thread(...).run()`. See updated answer. – George Mulligan Jan 24 '16 at 22:42