I'm trying to connect my device to a local server and send messages but I get this error when trying to connect: E/Error connect()(2016): android.os.NetworkOnMainThreadException . My code is this:
//Connect
public boolean Connect() {
//Get data from ip and port from editbox
String IP = ipinput.getText().toString();
int PORT = Integer.valueOf(portinput.getText().toString());
//This is where the error is shown
try {//create socket with IP + PORT values
miCliente = new Socket(IP, PORT);
//If it's connected
if (miCliente.isConnected() == true) {
return true;
} else {
return false;
}
} catch (Exception e) {
//Show error
txtstatus.setTextColor(Color.RED);
txtstatus.setText(" !!! ERROR !!!");
Log.e("Error connect()", "" + e);
return false;
}
}
I've tried the AsyncTask but maybe I'm doing it wrong and I'm new to sockets. And yes my server is running. Thanks
Add connect method in AsyncTask like below :
class MakeConnectionTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Connect();
return null;
}
}
And execute AsyncTask like this :
new MakeConnectionTask().execute();