1

I am new in this I want to send data from my android phone to my computer if i run it on my android phone it says android.os.NetworkOnMainThreadException can someone help me ?

public void OnClick1(View v) {

    try{
        Socket s=new Socket("localhost",4445);

        DataOutputStream dout =new DataOutputStream(s.getOutputStream());

        dout.writeUTF("hello");
        dout.flush();

        dout.close();
        s.close();

    } catch (Exception e){
        System.out.println(e);
    } 
}
Raedwald
  • 46,613
  • 43
  • 151
  • 237
SamSam
  • 31
  • 2
  • 5
  • 2
    Go to www.google.com and paste your query there . There are tons of result for your query. – Chirag Oct 16 '12 at 11:37
  • 1
    @SamSam: You may not perform network operations on the main thread as it blocks to user interface. Use a separate thread for it. The easiest way is to use the `AsyncTask` class. – Codo Oct 16 '12 at 11:38

5 Answers5

3

May be this can help you solving your issue

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);       
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
Festus Tamakloe
  • 11,231
  • 9
  • 53
  • 65
3

NetworkOnMainThreadException: The exception that is thrown when an application attempts to perform a networking operation on its main thread.

You can create an AsyncTask class as follows:

private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{

    @Override
    protected void onPostExecute(Void result) {
        //Task you want to do on UIThread after completing Network operation
        //onPostExecute is called after doInBackground finishes its task.
    }

    @Override
    protected Void doInBackground(Void... params) {
       //Do your network operation here
        return null;
    }
}

Also, don't forget to call the doInBackground() function, which can be easily called by using MyAsyncTask.execute(). Hope this helps..

Shekhar Chikara
  • 3,786
  • 2
  • 29
  • 52
  • so i have to put Socket s=new Socket("localhost",4445); .... in to de doinBackground part ? – SamSam Oct 16 '12 at 12:16
  • can you help me i am new in this – SamSam Oct 16 '12 at 13:28
  • Yes.. You should do all your networking tasks in doInBackground().. You can refer to the link mentioned in TechEnd's answer below for a good tutorial on using AsyncTask.. – Shekhar Chikara Oct 17 '12 at 04:02
  • i fix it ^^ but i have a delay he i receive it 3 min later – SamSam Oct 17 '12 at 12:11
  • Yep, this worked great - just put my method call for network request inside *doInBackground() {..}* . I found I didn't have to specify the generics which is nice to have 1 less complexity to deal with .. thanks! Also, don't forget .. to run the doInBackground() .. you have to call `myTask.execute()` on the the class instance extending AsyncTask – Gene Bo Oct 16 '15 at 18:55
  • @gnB Thanks for the suggestion. I have added your suggestions in my answer. – Shekhar Chikara Oct 19 '15 at 11:23
2

This work for me.

Please try to ip address inside of localhost

Android Permission:

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

Class RetrieveFeedTask code:

class RetreiveFeedTask extends AsyncTask<String, Void, Void> {

  private Exception exception;

  protected Void doInBackground(String... datas) {
     try {
        Socket s = new Socket("10.10.10.46", 8888);

        DataOutputStream dout = new DataOutputStream(s.getOutputStream());
        for (String string : datas) {
           dout.writeUTF(string);
        }

        dout.flush();
        dout.close();
        s.close();
     } catch (Exception e) {
        this.exception = e;
     }
     return null;
  }

  protected void onPostExecute(Void void1) {
     // do nothing;
  }

  public RetreiveFeedTask() {
  }

  public Exception getException() {
     return exception;
  }

}


 @Override
 public void onClick(View v) {
     switch (v.getId()) {
     case R.id.btn:

        RetreiveFeedTask feedTask = new RetreiveFeedTask();
        feedTask.execute(new String[] { "hello", "hello" });
        if (feedTask.getException() != null) {
           Log.d(TAG, feedTask.getException().toString());
        }
  }
Shekhar Chikara
  • 3,786
  • 2
  • 29
  • 52
Festus Tamakloe
  • 11,231
  • 9
  • 53
  • 65
1

Always use Threads, preferably AsyncTask, to perform network or any other time taking operations . Read this.

P.S. A little search on Google could give you hundreds of results.

Community
  • 1
  • 1
waqaslam
  • 67,549
  • 16
  • 165
  • 178
1

Try this AsyncTask tutorial. For best practice use Async methods.

for simple try this code in onCreate method

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().penaltyDeath().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().penaltyDeath().build());

But sometimes it is difficult to remember to make all the right things in your application during development. That is were StrictMode comes in. It allows to setup policies in your application to avoid doing incorrect things. For example the following setup will crash your application if it violates some of the Android policies. StrictMode should only be used during development and not in your live application.

Better avoid using StrictMode, go for using AsyncTask method.

Rahul Baradia
  • 11,802
  • 17
  • 73
  • 121