I am new to the Thread Concept. I am doing socket programming in android. I Want to use the message that I am receiving from client in various methods. But I am unable to access the message from run() method of Runnable interface. Below is my code
'''
class Thread1 implements Runnable {
@Override
public void run() {
Socket socket;
while (true) {
try {
serverSocket = new ServerSocket(SERVER_PORT);
socket = serverSocket.accept();
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = input.readLine();
if (message != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.setText("" message "\n");
}
});
} else {
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
'''
Here I want to use message variable in different class or methods.
CodePudding user response:
You can simple create a handler object in your activity like Handler activtyHandler = new Handler()
next pass this handler to the thread object that you are creating and then post whatever code you want to run on activity as follows
mHandler.post(new Runnable() {
@Override
public void run() {
tvMessages.setText("" message "\n");
}
});
CodePudding user response:
For your specific code make the message variable final:
final String message = input.readLine();
As a side note, where is tvMessages coming from? Clearly is a TextView, but how does it arrive to the class implementation? You should change tvMessages into a WeakReference instead of a strong reference, as using it as in your code may potentially produce an Activity context leak.
In addition, although not asked in the question, instead of creating a new runnable whenever receiving a message, it would be more efficient to create a Handler bound to the Main Thread before creating the worker thread, and then use it to send the messages to the UI. This will avoid a lot of unnecessary runnable instances.