i'm new in Android. I have the following code:
public class SettingsActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tcp_settings);
Button buttonConnect = (Button) findViewById(R.id.buttonConnect);
buttonConnect.setOnClickListener(new View.OnClickListener() {
EditText server_ip = (EditText) findViewById(R.id.set_server_ip);
EditText port = (EditText) findViewById(R.id.set_port);
@Override
public void onClick(View view) {
String serverAddr = server_ip.getText().toString();
String serverPort = port.getText().toString();
new connectTask().execute(serverAddr, serverPort);
}
});
}
class connectTask extends AsyncTask<String, Void, String> {
Socket socket;
@Override
protected String doInBackground(String... params) {
int servport = Integer.parseInt(params[1]);
try {
socket = new Socket(params[0], servport);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return params[0] + " : " + params[1];
}
}
}
I want to set a socket with server ip and port getting from EditTexts server_ip and port. In the connectTask I make a conversion from string to int in: int servport but i'm still getting error:
Caused by: java.lang.NumberFormatException: Invalid int "".
i have to make serverAddr to String because i have to put it in :
new connectTask().execute(serverAddr, serverPort);
But then socket require port as Int so conversion is required.
Could You help me and tell what i'm doing wrong ?
Your problem lies here within your code. You are passing in multiple parameters into a function that only receives one. Here is the def of execute: execute (Params... params)
new connectTask().execute(serverAddr, serverPort);
Change line to this:
new connectTask().execute(new String[]{serverAddr,serverPort});
Although the documentation does not say it, it is wanting an array of the first template object being passed in IF you are passing in more than one parameter.