i have a sockets program in android, i want to send a command or text message by clicking button on the client side. and send a different text message depending on which button is pressed. but i am getting the complier error message about the “out” PrintWriter object from
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
if i use this “out” inside of an onclick listener, how do i fix this compiler error? I don’t really want to make this a final variable as recommended by the compiler as a fix.
here is the code shown below with the two onclick button listeners inside of the run() method for sending massage by socket from client to server android app
if you click the sendA button it sends the text message “testA” and if you click the sendB button it sends the text message “testB”
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 8080);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
sendA.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
out.println("testA");
}
});
sendB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
out.println("testB");
}
});
// where you issue the commands
// out.println("testX");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
Putting final will clear your error.
But like you said you dont want
final, then why not declareoutas a global variable?