-1

I want to perform network operation in other class. I have created a Runnable in MainActivity but I am having the exception NetworkOnMainThreadException

My question is do Runnable is not creating another thread from UI thread? I am new to Android development.

MainActivity.java

 //Inside MainActivity Class
//.....
Runnable initStack = new Runnable(){
   @Override 
   public void run(){
      otherClassObject.itsMethod();
      handler.post(new Runnable(){
             //back to UI thread.... 
    });
  }
}
mubeen
  • 813
  • 2
  • 18
  • 39

4 Answers4

2

My question is do Runnable is not creating another thread from UI thread?

No. A Runnable is not a Thread. If you want a Thread, use a Thread, or use something else that uses a Thread (e.g., AsyncTask).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Ok.. Got it. Thank you. I ask this question because I found tutorial about handler, they implement like above code(my code); Explaining handler class etc. – mubeen Mar 23 '15 at 17:55
  • 2
    @mubeen: By default, a `Handler` is tied to the main application thread, and `post()` will trigger a call to `run()` on the `Runnable` on the main application thread. You can specifically create a `HandlerThread` to have a `Handler` that is not associated with the main application thread, but this is an advanced technique and not one that many Android developers use. Usually, Android developers will use `AsyncTask`, `IntentService`, etc. – CommonsWare Mar 23 '15 at 17:59
2

You need to create a new Thread, not only a runnable. Instead of calling initStack.run(), do the following: new Thread(initStack).start();

Brian
  • 1,318
  • 1
  • 16
  • 33
1

possible duplicate of: NetworkOnMainThreadException on Runnable

According to java documentation, "should be implemented by any class whose instances are intended to be executed by a thread."

In a nutshell, Android has made some changes to handling of network related thread on the main thread. It is done by AsyncTask.

Read about it here: http://developer.android.com/reference/android/os/AsyncTask.html

Also, it would be better if you would go through the basics of Android programming and some tutorials before you take a leap of faith into the actual coding part.

Community
  • 1
  • 1
Surya Teja Karra
  • 541
  • 1
  • 6
  • 19
0

Change your code to. Runnable is donot create thread. Runnable is simple three lines interface.

new Thread() {
            @Override
           public void run() {
               //your code here
           }
       }.start();