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);
    } 
}
2
  • 2
    Go to www.google.com and paste your query there . There are tons of result for your query. Commented Oct 16, 2012 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. Commented Oct 16, 2012 at 11:38

5 Answers 5

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

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..

6 Comments

so i have to put Socket s=new Socket("localhost",4445); .... in to de doinBackground part ?
can you help me i am new in this
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..
i fix it ^^ but i have a delay he i receive it 3 min later
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
|
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());
        }
  }

Comments

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.

1 Comment

i dont know how to use AsyncTask can you help me ?
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.

1 Comment

nop the tutorials didnt help me but thanks for trying to help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.