-4

When running the line echoSocket = new Socket(serverHostname, 10008); My app crashes with error, NetworkOnMainThreadException error.

From what i have seen this related to trying to run Sockets on the UI thread. so how can i change my code (below) so it works?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;

public class MainActivity extends ActionBarActivity  {

    Button Bgo;
    private static TextView TV1;
    EditText Text;
    String userInput;
    Socket echoSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    String Responce = null;
    String serverHostname;
    int section = 0;
    Boolean keepgoing = true;
    Boolean g1o = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bgo = (Button) findViewById(R.id.Go);
        TV1 = (TextView) findViewById(R.id.tv1);
        Text = (EditText) findViewById(R.id.Inputtext);
        onclick();
    }

    public void send() {

        // System.out.println("type the host name"); ->>updating
        // serverHostname = new String(stdIn.readLine());

        serverHostname = new String("192.168.1.105");
        System.out.println("Attemping to connect to host " + serverHostname
                + " on port 10008.");

        try {
            echoSocket = new Socket(serverHostname, 10008);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                    echoSocket.getInputStream()));

        } catch (UnknownHostException e) {
            TV1.setText("Don't know about host: " + serverHostname);
        } catch (IOException e) {
            TV1.setText("Couldn't get I/O for " + "the connection to: "
                    + serverHostname);
        }

        TV1.setText("type VIEW-LOG for last 5 enteries (newset first) or DC to dissconect");
    }

    public void onclick() {
        Bgo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (g1o = true) {
                    TV1.setText("conecting");
                    g1o = false;
                    send();
                } else {
                    userInput = Text.getText().toString();
                    try {
                        if (userInput.equals("VIEW-LOG")) {
                            out.println(userInput);
                            int i = 0;
                            while (i < 5) {

                                Responce = in.readLine();

                                System.out.println(Responce);//this will be replace once this is working
                                i++;
                            }
                        } else if (userInput.equals("DC")) {
                            keepgoing = false;
                            System.out.println("dc");
                            out.println(userInput);
                        } else {
                            out.println(userInput);

                            System.out.println(in.readLine());

                        }
                    } catch (IOException e) {

                    }

                }
            }
        });
    }

    public void Close() {

        try {
            out.close();
            in.close();
            echoSocket.close();
        } catch (IOException e) {

        }
    }
}

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="PlaceHolder"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/Inputtext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/Go"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go" />

</LinearLayout>

What this dose: one one button press it runs send(); that make the conection to a server. when it is pressed again it send the test in the edittext to the server and if it is DC it disconects from the server, if it is VIEW-LOG the server sends 5 lots of strings

Tom Hazell
  • 15
  • 1
  • 1
  • 8
  • 3
    There are multiple answers in SO on this, use Async task to do network request. I would suggest to check other answers before asking questions. – Libin May 09 '14 at 16:48
  • 1
    [Strongly related](https://www.google.com/search?q=networkonmainthreadexception&oq=NetworkOnMain&aqs=chrome.1.69i57j0l5.6273j0j8&sourceid=chrome&es_sm=122&ie=UTF-8) – codeMagic May 09 '14 at 16:51

2 Answers2

0

This exception raises when you perform some network operation on main thread which android does not allow to do. Move your send method call to non-UI thread or better move your code into AsyncTask.

Software Engineer
  • 3,906
  • 1
  • 26
  • 35
Waqar Ahmed
  • 5,005
  • 2
  • 23
  • 45
-1

You should not perform any network related operation on main thread.

Either use a Handler http://developer.android.com/reference/android/os/Handler.html

OR

an AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html

Software Engineer
  • 3,906
  • 1
  • 26
  • 35
Fareya
  • 1,523
  • 10
  • 11