java – Socket connection throws an exception on Android

Question:

The code below works perfectly when only used with a JButton, but when passing it to Android, an exception (Exception) occurs.

I found the error is in

clientSocket = new Socket(serverIP, serverPort);

but I can not understand why the error.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button button;

private static final String serverIP="192.168.1.177";
private static final int serverPort=80;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    button = (Button)findViewById(R.id.buttonID);

    button.setOnClickListener(new ButtonListener());    

}

public class ButtonListener implements OnClickListener{

    @Override
    public void onClick(View v) {


        // Message that will be sent to Arduino
        String msgToServer;

        // Received message will be stored here
        String msgFromServer;

        try{

            // Making the socket connection
            Socket clientSocket = new Socket(serverIP, serverPort);

            // Debug
            System.out.println("Connected to:"+serverIP+" on port:"+serverPort);


            // OutputStream to Arduino-Server
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

            //BufferedReader from Arduino-Server
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            // Message tha will be sent
            msgToServer = "Turn ON LED 13";

            // Sending the message
            outToServer.writeBytes(msgToServer + '\n');

            // Debug
            System.out.println("sending to Arduino-Server: "+msgToServer);

            // Recieving the answer
            msgFromServer = inFromServer.readLine();

            // Print the answer
            System.out.println("recieved from Arduino-Server: " + msgFromServer);

            // Close the socket. Don't do this if you want to keep the connection
            clientSocket.close();

        }

        catch(Exception e){

        }

    }

}   

}       

Answer:

As Lucas said, Make sure your AndroidManifest.xml has the following permissions:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Hugs

Scroll to Top