-2

I am new to android. My project is related to networking. I am getting this error FATAL EXCEPTION: main

android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java1133)

... ...

My code is :

package com.example.simpleclientactivity;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;

    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class SimpleClientActivity extends Activity {

     private Socket client;
     private PrintWriter printwriter;
     private EditText textField1;
     private Button button;
     private String messsage;

     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      textField1 = (EditText) findViewById(R.id.editText1); //reference to the text field
      button = (Button) findViewById(R.id.button1);   //reference to the send button

      //Button press event listener
      button.setOnClickListener(new View.OnClickListener() {

       public void onClick(View v) {

          Context context = getApplicationContext();
          CharSequence text = "Hello toast!";
          int duration = Toast.LENGTH_SHORT;

          Toast toast = Toast.makeText(context, text, duration);
          toast.show();
          messsage = textField1.getText().toString(); //get the text message on the text field      
          textField1.setText("");      //Reset the text field to blank

          try {

                 client = new Socket("10.0.2.2", 4444);  //connect to server
                 printwriter = new PrintWriter(client.getOutputStream(),true);
                 printwriter.write(messsage);  //write the message to output stream

                 printwriter.flush();
                 printwriter.close();
                 client.close();   //closing the connection

                } catch (UnknownHostException e) {
                 e.printStackTrace();
                } catch (IOException e) {
                 e.printStackTrace();
                }
        }
      });

     }
    }

Here is main.xml code

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"`enter code here`
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="83dp"
        android:ems="10"
        android:text="Client" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="53dp"
        android:text="Send" />

</RelativeLayout>

It's not even displaying the toast message after clicking the button. However it's showing error in android.os.NetworkOnMainThreadException.

Ankit
  • 6,554
  • 6
  • 49
  • 71
Avog
  • 139
  • 17

4 Answers4

1

Try this..

This exception is thrown when an application attempts to perform a networking operation on its main thread

 button.setOnClickListener(new View.OnClickListener() {

       public void onClick(View v) {

          Context context = getApplicationContext();
          CharSequence text = "Hello toast!";
          int duration = Toast.LENGTH_SHORT;

          Toast toast = Toast.makeText(context, text, duration);
          toast.show();
          messsage = textField1.getText().toString(); //get the text message on the text field      
          textField1.setText("");      //Reset the text field to blank

            new MyClass().execute(messsage);


        }
      });

MyClass.class AsyncTask

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

    private Exception exception;

    protected String doInBackground(String... messsage) {
        try {

                 client = new Socket("10.0.2.2", 4444);  //connect to server
                 printwriter = new PrintWriter(client.getOutputStream(),true);
                 printwriter.write(messsage);  //write the message to output stream

                 printwriter.flush();
                 printwriter.close();
                 client.close();   //closing the connection

                } catch (UnknownHostException e) {
                 e.printStackTrace();
                } catch (IOException e) {
                 e.printStackTrace();
                }
    }

    protected void onPostExecute(String result) {
        // TODO: check this.exception 
        // TODO: do something with the feed
    }
}

You cannot perform network IO on the UI thread on Honeycomb. Technically it is possible on earlier versions of Android, but is a really bad idea as it will cause your app to stop responding, and can result in the OS killing your app for being badly behaved. You'll need to run a background process or use AsyncTask to perform your network transaction on a background thread.

There is an article about Painless Threading on the Android developer site which is a good introduction to this, and will provide you with much better depth of answer than can be realistically provided here.

Hariharan
  • 24,741
  • 6
  • 50
  • 54
0

You have to put your code that access the internet on a thread

new Thread(new Runnable(){
  @Override
  public void run(){
    //your code that access internet here
  }
}).start();
Rick Royd Aban
  • 904
  • 6
  • 33
0

try this code

   package com.example.simpleclientactivity;
   import java.io.IOException;
  import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SimpleClientActivity extends Activity {

 private Socket client;
 private PrintWriter printwriter;
 private EditText textField1;
 private Button button;
 private String messsage;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  textField1 = (EditText) findViewById(R.id.editText1); //reference to the text field
  button = (Button) findViewById(R.id.button1);   //reference to the send button

  //Button press event listener
  button.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {

      Context context = getApplicationContext();
      CharSequence text = "Hello toast!";
      int duration = Toast.LENGTH_SHORT;

      Toast toast = Toast.makeText(context, text, duration);
      toast.show();
      messsage = textField1.getText().toString(); //get the text message on the text field      
      textField1.setText("");      //Reset the text field to blank

    new GetCategory().execute(message);
    }
  });

 }


    //add inner class

   class GetCategory extends AsyncTask<Void, Void, ArrayList<AbstractDetail>>{



    protected  ArrayList<AbstractDetail>  doInBackground(String... messsage) {
        try {

             client = new Socket("10.0.2.2", 4444);  //connect to server
             printwriter = new PrintWriter(client.getOutputStream(),true);
             printwriter.write(messsage);  //write the message to output stream

             printwriter.flush();
             printwriter.close();
             client.close();   //closing the connection

            } catch (UnknownHostException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            }
        return null;

    }

    protected void onPostExecute(ArrayList<AbstractDetail> result)
    {


        }

    }


}






}
Dev
  • 3,410
  • 4
  • 17
  • 16
0

Problem

  • You can not access network over UI thread. You are accessing Network through UI thread that's why you are getting NetworkOnMainThreadException.

Solution

  • Create new thread and access Network over that Thread. OR
  • Use AsyncTask to do network related work on doInBackgroung() and for updating UI onPostExecute().
Vishesh Chandra
  • 6,951
  • 6
  • 35
  • 38