0

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:

  1. The first one initializes some parameters, connects to the socket
  2. 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.

Sastrija
  • 3,284
  • 6
  • 47
  • 64
KDX2
  • 945
  • 2
  • 14
  • 31
  • 1
    ALso, calling Run does not start a thread. Thread.start() starts a thread. Calling run on a Runnable runs it in the current thread. – Gabe Sechan Mar 21 '16 at 17:17
  • @GabeSechan good but just two more things. Isn't the AsyncTask for threads which last for just a couple of seconds? In my case the thread I use should be constantly running alongside the UI (main) one, I guess. Correct me if I'm wrong, if I say ClientSide.run() it will mean that I will be running it within the main thread, not on background as a separate process? And vice versa - ClientSide.start() will run it on background? – KDX2 Mar 21 '16 at 17:22
  • AsyncTask is a good thread replacement if you need it for a couple of seconds and then update the UI, like downloading an image. If you need it to run for a long time then you want a normal Thread. – Gabe Sechan Mar 21 '16 at 17:25
  • @GabeSechan thank you, ok and how about the second question? (sorry for asking so much, it is fundamental, I need to get it :D :D :D ) – KDX2 Mar 21 '16 at 17:26
  • No you have to make a new Thread object and pass it ClientSide as a runnable in its constructor. Then call start on the Thread. It will launch a new OS level thread, then call run on that new thread. – Gabe Sechan Mar 21 '16 at 17:27
  • @GabeSechan Thank you so much, excuse me for taking you so much time, if there was a like-this-post kind of option in the comment section I'd had voted for those answers, thanks. – KDX2 Mar 21 '16 at 17:29

0 Answers0