0

My classmate and I are trying to design a new app, but we are stuck with a problem.
We are trying to connect our Raspberry with the phone through a socket in order to send a message. We have edited some code from internet so as to fit our application (that code worked perfectly). We haven't done too many changes on that but we don't know why it's not working while even the methods and everything is the same. I've looked for the error but with no success. I've been reading something about asynchronous tasks but the other code that I wrote didn't work either. I publish the methods of the two classes I'm working on.

We want that when the method enviar() is called from a button of the layout get the info from a ListView, put everything in a string, open a socket, send the message and close the socket. The part of the string is completely well, but when it calls other classes' methods throws an exception that we don't know how to solve.

Note: the println-s are the particular way we have to debug the app. Don't hit us, please

Here is the code:

Method enviar

public void enviar(View view){
    // get the row the clicked button is in
    int i = 0;
    String eskaera="";
    Sockettest sckt = new Sockettest();

    //Conectar
    boolean conectstatus = sckt.Connect();
    if (conectstatus) {//mostramos mensaje 
        System.out.println("Conexion OK ");

    } else {//error al conectarse 
        //mostramos msg de error
        System.out.println("Error.. ");
    }

    while (i < obtenerItems().size()) {
        ListView lv = (ListView)findViewById(R.id.listViewBokatas);
        LinearLayout lerroa = (LinearLayout) lv.getChildAt(i);
        TextView bokata = (TextView) lerroa.getChildAt(0);
        EditText kantitatea = (EditText) lerroa.getChildAt(2); 
        int balioa = Integer.parseInt(kantitatea.getText().toString());
        if (balioa != 0) {
            eskaera+=balioa + " X " + bokata.getText().toString() +"\n";
        }
        i++;
    }
    System.out.println(eskaera);
    sckt.Snd_txt_Msg(eskaera);
    sckt.Disconnect();
    //return eskaera;
}

Class Sockettest

public class Sockettest  {
/** Called when the activity is first created. */

Socket miCliente;

ObjectOutputStream oos;
ObjectInputStream ois;
Mensaje_data mdata;



//Conectamos
public boolean Connect()  {
    //Obtengo datos ingresados en campos
    String IP = "viserion.no-ip.biz";
    int PORT = Integer.valueOf("5555");


    try {//creamos sockets con los valores anteriores
        System.out.println("ERROR DE LOS GORDOS0");
        miCliente = new Socket("viserion.no-ip.biz", 5555);
        System.out.println("ERROR DE LOS GORDOS2");
        //si nos conectamos
        if (miCliente.isConnected() == true) {
            return true;
        } else {
            System.out.println("ERROR DE LOS GORDOS");
            return false;
        }
    } catch (Exception e) {
        //Si hubo algun error mostrmos error
        System.out.println("ERROR DE LOS GORDOS3");
        Log.e("Error connect()", "" + e);
        return false;
    }
}

//Metodo de desconexion
public void Disconnect() {
    try {
        //Prepramos mensaje de desconexion
        Mensaje_data msgact = new Mensaje_data();
        msgact.texto = "";
        msgact.last_msg = true;
        //avisamos al server que cierre el canal
        boolean val_acc = Snd_Msg(msgact);

        if (!val_acc) {//hubo un error
            System.out.println(" Error  ");
            Log.e("Disconnect() -> ", "!ERROR!");

        } else {//ok nos desconectamos
            System.out.println("Desconectado");
            //camibmos led a rojo
            Log.e("Disconnect() -> ", "!ok!");
            //cerramos socket   
            miCliente.close();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}



//Envio mensaje de texto 
public void Snd_txt_Msg(String txt) {

    Mensaje_data mensaje = new Mensaje_data();
    //seteo en texto el parametro  recibido por txt
    mensaje.texto = txt;
    //no es el ultimo msg
    mensaje.last_msg = false;
    //mando msg
    boolean val_acc = Snd_Msg(mensaje);
    //error al enviar
    if (!val_acc) {
        System.out.println(" Error  ");
        Log.e("Snd_txt_Msg() -> ", "!ERROR!");
    }
}

/*Metodo para enviar mensaje por socket
 *recibe como parmetro un objeto Mensaje_data
 *retorna boolean segun si se pudo establecer o no la conexion
 */
public boolean Snd_Msg(Mensaje_data msg) {

    try {
        //Accedo a flujo de salida
        oos = new ObjectOutputStream(miCliente.getOutputStream());
        //creo objeto mensaje
        Mensaje_data mensaje = new Mensaje_data();

        if (miCliente.isConnected())// si la conexion continua
        {
            //lo asocio al mensaje recibido
            mensaje = msg;
            //Envio mensaje por flujo
            oos.writeObject(mensaje);
            //envio ok
            return true;

        } else {//en caso de que no halla conexion al enviar el msg
            System.out.println("Error...");//error
            return false;
        }

    } catch (IOException e) {// hubo algun error
        Log.e("Snd_Msg() ERROR -> ", "" + e);

        return false;
    }
}
}

The LogCat

03-26 21:48:45.636: I/System.out(27379): ERROR DE LOS GORDOS0
03-26 21:48:45.636: I/System.out(27379): ERROR DE LOS GORDOS3
03-26 21:48:45.636: E/Error connect()(27379): android.os.NetworkOnMainThreadException
03-26 21:48:45.636: I/System.out(27379): Error.. 
03-26 21:48:45.676: I/System.out(27379): 3 X Bacon-Queso
03-26 21:48:45.676: I/System.out(27379): 1 X Jamaica
03-26 21:48:45.676: D/AndroidRuntime(27379): Shutting down VM
03-26 21:48:45.676: W/dalvikvm(27379): threadid=1: thread exiting with uncaught exception (group=0x2b542210)
03-26 21:48:45.736: E/AndroidRuntime(27379): FATAL EXCEPTION: main
03-26 21:48:45.736: E/AndroidRuntime(27379): java.lang.IllegalStateException: Could not execute method of the activity
03-26 21:48:45.736: E/AndroidRuntime(27379):    at android.view.View$1.onClick(View.java:3063)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at android.view.View.performClick(View.java:3534)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at android.view.View$PerformClick.run(View.java:14263)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at android.os.Handler.handleCallback(Handler.java:605)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at android.os.Looper.loop(Looper.java:137)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at android.app.ActivityThread.main(ActivityThread.java:4441)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at java.lang.reflect.Method.invokeNative(Native Method)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at java.lang.reflect.Method.invoke(Method.java:511)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at dalvik.system.NativeStart.main(Native Method)
03-26 21:48:45.736: E/AndroidRuntime(27379): Caused by: java.lang.reflect.InvocationTargetException
03-26 21:48:45.736: E/AndroidRuntime(27379):    at java.lang.reflect.Method.invokeNative(Native Method)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at java.lang.reflect.Method.invoke(Method.java:511)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at android.view.View$1.onClick(View.java:3058)
03-26 21:48:45.736: E/AndroidRuntime(27379):    ... 11 more
03-26 21:48:45.736: E/AndroidRuntime(27379): Caused by: java.lang.NullPointerException
03-26 21:48:45.736: E/AndroidRuntime(27379):    at com.eetam.ibokata.Sockettest.Snd_Msg(Sockettest.java:103)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at com.eetam.ibokata.Sockettest.Snd_txt_Msg(Sockettest.java:87)
03-26 21:48:45.736: E/AndroidRuntime(27379):    at com.eetam.ibokata.BokatasActivity.enviar(BokatasActivity.java:131)
03-26 21:48:45.736: E/AndroidRuntime(27379):    ... 14 more

I believe in you guys! Thanks everyone is looking for a solution and I'll be very pleased for all of you. Thank you so much!

Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
MuGiK
  • 351
  • 4
  • 13
  • What is on line 103 of Sockettest.java? – Aleks G Mar 26 '14 at 20:52
  • oos = new ObjectOutputStream(miCliente.getOutputStream()); – MuGiK Mar 26 '14 at 20:54
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) - the only thing you have unique here is a poorly chosen exception handler which absorbs that, so you survive to crash later with a null object. – Chris Stratton Mar 26 '14 at 21:27

2 Answers2

1

In your logcat you have line

ERROR DE LOS GORDOS0

followed by line

ERROR DE LOS GORDOS3

Following your code in the Connect method, this means that line

miCliente = new Socket("viserion.no-ip.biz", 5555);

was the one that threw Exception e - and as a result your miCliente variable was not initialised and remained null. When you then on line 103 attempted to do miCliente.getOutputStream() you ended up with a NullPointerException.

Now, if you read your logcat carefully, you'll see that the error thrown is NetworkOnMainThreadException - which means that you're trying to connect your socket from the main UI thread. Android does not allow it (or at least newer versions don't allow this). Put your connect/send-message/disconnect code inside a separate thread (e.g. AsyncTask) - and you will probably be ok.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
0

miCliente is probably null.

ERROR DE LOS GORDOS3 -> this means that something threw exception in Connect method and that was probably before miCliente was set -> null pointer exception.

And that is caused by NetworkOnMainThreadException. Look here How to fix android.os.NetworkOnMainThreadException?

Community
  • 1
  • 1
jakub.petr
  • 2,951
  • 2
  • 23
  • 34
  • I know, that's why I'm posting this here. I believe that the socket is perfecly created: gets the IP (String) and the Port (int). I don't know why, then, it's a null. After the declaration should be created. – MuGiK Mar 26 '14 at 21:00
  • Look here http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception. – jakub.petr Mar 26 '14 at 21:01