I’m new to programming in android and I need help to build an application. I want two phones to connect to each other, one being the client and the other being the server. I want the client to have 2 stages. In the first the user would input the ip of the server y click on a button to stablish the connection. In the second one the user would input a message and click on a button to send it to the server.
The code shown bellow is to send the string “message” to the server but as I was saying I want the user to be able to input the string. I don’t know how to tackle his issue, do I need a second activity to be called once the connection is established in the activity I show bellow? In that case I wouldn’t know how to pass a socket to another activity, I only know how to pass strings. Besides, I would need another button and therefore a new OnClickListener and I would still need to pass the socket to that function.
Without using a second activity I don’t know how to make the second input field (the one where the user would input the message to send to the server) to show up once the connection is established. The views (layout.xml) for this activity are already associated to the same, I can’t just clear the screen and create a new EditText field on the fly.
I hope I made myself clear.
Thanks in advance
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
**out.println("messageToSend");**
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
I don’t think , you need a second activity to send message over socket.
Anyways , It depends on you design —
you can have two editTexts at a same but their visibility would be different.
serverIpAddressET can be visible when user has not provided socket IP.
Once connection is established , you can change the visibility of serverIpAddressET to the Gone and make Visible the messageET .