Issue
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.
Solution
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");
}
});
Answered By - Taranmeet Singh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.