-3

i am using an example to learn the use of sockets in android. i'm kind of new to this and I'm using a book to learn. I can't really figure out whats the problem, as the example is literally copied from the book, except for the IP, which is my computer's. the android app keeps throwing this error:

error:android.os.NetworkOnMainThreadException

I post the code:

as some words are in spanish i will translate them for you, just in case it makes it easier to understand:

PUERTO-->port,ENTRADA-->input,SALIDA-->output,ENVIANDO-->sending,HOLA MUNDO-->hello world,RECIBIENDO-->receiving,DATOS-->data,CLIENTE-->client

ANDROID CLIENT

    package com.jacho981.clienteecho;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ClienteECHO extends Activity {

    private TextView output;

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

        output = (TextView) findViewById(R.id.TextView01);
        ejecutaCliente();
    }

    private void ejecutaCliente() {
        // String ip = "158.42.146.127";
        String ip = "192.168.1.3";
        int puerto = 7;

        log(" socket " + ip + " " + puerto);

        try {
            Socket sk = new Socket(ip, puerto);
            BufferedReader entrada = new BufferedReader(new InputStreamReader(
                    sk.getInputStream()));
            PrintWriter salida = new PrintWriter(new OutputStreamWriter(
                    sk.getOutputStream()), true);

            log("enviando...");

            salida.println("Hola Mundo");

            log("recibiendo..." + entrada.readLine());

            sk.close();
        } catch (Exception e) {
            log("error: " + e.toString());
        }

    }

    private void log(String string) {
        output.append(string + "\n");
    }

}

JAVA SERVER

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServidorECHO {

    public static void main(String args[]) {
        try {
            ServerSocket sk = new ServerSocket(7);
            while (true) {
                Socket cliente = sk.accept();
                BufferedReader entrada = new BufferedReader(
                        new InputStreamReader(cliente.getInputStream()));
                PrintWriter salida = new PrintWriter(new OutputStreamWriter(
                        cliente.getOutputStream()), true);
                String datos = entrada.readLine();
                salida.println(datos);
                cliente.close();
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}
jacho981
  • 87
  • 1
  • 10
  • 3
    Before you ask with an exclamation point, I'd like you to take a step back and look at the error you get, "network on main thread exception". Googling this error will show you multiple results helping you to fix it. You need to mvoe your network code off the main thread. – nanofarad Oct 30 '13 at 20:15
  • http://stackoverflow.com/a/18678258/826657 see this ! – Rachit Mishra Oct 30 '13 at 20:20
  • 1
    duplicate of just any question with networkonmainthreadexception in the title. – njzk2 Oct 30 '13 at 20:20

2 Answers2

1
android.os.NetworkOnMainThreadException

You are doing time taking operations on main gui, which may stuck the user, or even hang the ui, you need an AsyncTask to perform the network operations in main thread,

For more info about AsyncTasks

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

on Android Honeycomb and above the application will crash with NetworkOnMainThreadException, but will work on earlier versions.

From the developer reference

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Rachit Mishra
  • 6,101
  • 4
  • 30
  • 51
0

This is the Exception people getting in Android Jellybean and say,"The same code works in lower versions, but not in jellybean".

Solution is, You have to move your network operation from main thread to a bachground thread.
AsyncTask is a good solution. Here is a nice toutorial on Android Background processing

Nizam
  • 5,698
  • 9
  • 45
  • 57