I am currently working on a simple android app, which on a pressed button must start a networking thread. The networking thread listens for something new on the socket and reads it. The problem is that, when I press the button the application crashes. I was able to track down the error and it says:
E/AndroidRuntime: FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
So, in the onCreate()
I initialize the button and I say the following:
fab2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplication(), "Connect", Toast.LENGTH_SHORT).show();
new ClientSide().run();
}
});
The ClientSide is a separately written .java file consisting of two threads:
- The first one initializes some parameters, connects to the socket
The second one listens and writes from/to the socket (
class TextDataTransmitter extends Thread
)public class ClientSide extends RuntimeException implements Runnable{ ... System.out.println("Thread activated!"); // Connect to the chat server...}
The compilation doesn't even reach the
System.out.println("Thread blablabla")
...
Please guys advice me what to do in order to make this crash disappear. I am still far from being advanced at android development. If you need more info or code, I'll be ready to provide it.