Set text in thread class from activity - android

I have two classes, one is Activity, and one is Thread class:
Activity:
public class MainActivity extends AppCompatActivity {
ObjectInputStream inFromServer = null;
ObjectOutputStream outToServer=null;
Socket clientSocket = null;
String userName;
EditText message;
static TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
message = (EditText)findViewById(R.id.txtMessage);
textView = (TextView)findViewById(R.id.textView);
try {
clientSocket = new Socket("10.0.0.41", 10002);
outToServer =
new ObjectOutputStream(clientSocket.getOutputStream());
inFromServer =
new ObjectInputStream((clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
ReceiveMessages receiveMessages = new ReceiveMessages(inFromServer);
receiveMessages.start();
}
public void onClickSend(View view) throws IOException {
outToServer.writeObject("Eliran!" + message.getText().toString());
}
public void btnUserName(View view) throws IOException {
EditText editText = (EditText)findViewById(R.id.userName);
userName = editText.getText().toString();
outToServer.writeObject(userName + "!");
}
}
Thread class:
public class ReceiveMessages extends Thread {
ObjectInputStream inFromServer = null;
public ReceiveMessages(ObjectInputStream inFromServer)
{
this.inFromServer = inFromServer;
}
public void run() {
try {
while (true) {
String message = (String) inFromServer.readObject();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I want to set text in the text view of the activity in the Thread class.
How can I do it? InflateLayout isn't helping I think.

I would go about it by creating a Callback that gets called when the String is received from the aerver.
interface ReceiveMessageListener {
void onMessageReceived (String message);
}
Then have my Activity implement the interface and set the text in the onMessageReceived call back.
#Override
public void onMessageReceived (String message) {
runOnUiThread(new Runnable() {
#Override
public void run () {
textView.setText(message);
}
});
}
You'll also have to change the constructor for your MessageReceive class to take a MessageReceiveListener.
From your Activity:
ReceiveMessages receive = new ReceiveMessages(input, this);

Only the UI thread can interact with ui elements (such textview). Try using runOnOiThread or mainHandler.post ()

Related

Problems in change text of a textview

I have a problem in change a text of a textview in android, i'm starting in android, ok I want do a chat with sockets, I made the socket and connected on server but i can't change the text of the textview, ok this is the code:
public class Cliente extends Activity {
Button conect;
Button env;
EditText ip;
EditText nome;
EditText msg;
String nome_txt;
String ip_txt;
Socket cl;
String texto = "";
TextView log;
boolean a = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
conect = (Button) findViewById(R.id.conect);
env = (Button) findViewById(R.id.env);
msg = (EditText) findViewById(R.id.msg);
ip = (EditText) findViewById(R.id.ip_tx);
nome = (EditText) findViewById(R.id.nm_tx);
log = (TextView) findViewById(R.id.log);
conect.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
ip_txt = ip.getText().toString();
nome_txt = nome.getText().toString();
setContentView(R.layout.activity_cliente);
Thread th =new Thread(new Ct());
Log.d("Iniciado", "th");
log.setText("asd");
th.start();
}
});
env.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
envMSG(msg.getText().toString());
msg.setText("");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void envMSG(String msg) throws IOException {
DataOutputStream outToServer = new DataOutputStream(cl.getOutputStream());
outToServer.writeBytes(msg + '\n');
}
public String serOUT() {
try{
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(cl.getInputStream()));
if (inFromServer.ready()) {
String texto = inFromServer.readLine();
return texto;
} else {
return null;
}
}catch(IOException e){
return null;
}
}
public class Ct extends Thread implements Runnable{
#Override
public void run() {
try {
cl = new Socket(ip_txt, 1111);
envMSG(nome_txt);
do{
String tx = serOUT();
if (tx != null) {
texto += tx + "\n";
log.setText(texto);
envMSG("ola");
}
Log.d("Status",cl.isClosed()+"");
this.sleep(10);
}while (true);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Please tell the error reason, and show examples.
Thanks for Reading.
ass.:Lucas Avelino
First of all, you cant set text inside thread, you have to ovveride runOnUiThread method and try to set text in this method.
public class Ct extends Thread implements Runnable{
#Override
public void run() {
try {
cl = new Socket(ip_txt, 1111);
envMSG(nome_txt);
do{
String tx = serOUT();
if (tx != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
texto += tx + "\n";
log.setText(texto);
envMSG("ola");
}
});
}
Log.d("Status",cl.isClosed()+"");
this.sleep(10);
}while (true);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

How to pass asynctask to another activity in android?

I'm try to writing an online game with a socket connection.
So I use asynctask to make a socket connection.
SocketServer.java
public class SocketServer{
private MyCustomListener listener;
private String ip = "127.0.0.1";
private int port = 4444;
#SuppressWarnings("unused")
private Context context;
private SocketAsync socketAsync;
private String dataInput, username;
public SocketServer(Context context) {
this.context = context;
}
public void setOnRecieveMsgListener(MyCustomListener listener) {
this.listener = listener;
}
public void connect() {
socketAsync = new SocketAsync();
socketAsync.execute();
}
public void sentData(String x, String y, String z) {
dataInput = null;
JSONObject object = new JSONObject();
// JSON Encode
socketAsync.sentJSON(object);
}
private class SocketAsync extends AsyncTask<Void, Void, String> {
private Socket socket;
private PrintWriter printWriter;
#Override
protected String doInBackground(Void... params) {
try {
socket = new Socket(InetAddress.getByName(ip),port);
OutputStreamWriter streamOut = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
printWriter = new PrintWriter(streamOut);
streamOut.flush();
BufferedReader streamIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
Looper.prepare();
while(socket.isConnected()) {
try {
dataInput = streamIn.readLine();
listener.onRecieveMessage(new MyListener(dataInput));
}
catch(Exception e) {}
}
Looper.loop();
}
catch(Exception e) {}
return null;
}
public void sentJSON(JSONObject object) {
if(socket.isConnected()) {
try {
printWriter.println(object.toString());
printWriter.flush();
}
catch(Exception e) {}
}
}
}
}
Login.class
public class Login extends Activity implements MyCustomListener {
JSONObject object;
SocketServer socketserver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
socketserver = new SocketServer(this);
socketserver.setOnRecieveMsgListener(this);
socketserver.connect();
button();
}
private void button() {
Button loginBt = (Button)findViewById(R.id.login_bt);
final EditText un = (EditText)findViewById(R.id.username);
final EditText ps = (EditText)findViewById(R.id.password);
final String[] logindata = new String[2];
loginBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logindata[0] = un.getText().toString();
logindata[1] = ps.getText().toString();
socketserver.setUsername(logindata[0]);
socketserver.sentData("SERVER", "TEST", "login");
}
});
}
private void toMainScreen() {
Intent x = new Intent(this,Main.class);
startActivity(x);
}
#Override
public void onRecieveMessage(MyListener ml) {
try {
JSONObject json = new JSONObject(ml.getMsgStr());
System.out.println(json.getString("content"));
if(json.getString("content").equals("TRUE")) {
toMainScreen();
}
else
Toast.makeText(getApplicationContext(), "Login Fail", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.e("## JSON DECODE", e.toString());
e.printStackTrace();
}
}
}
Main.class
public class Main extends Activity implements MyCustomListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//do some thing
}
#Override
public void onRecieveMessage(MyListener ml) {
System.out.println("MAIN : " + ml.getMsgStr());
}
}
so how can I pass object "socketserver" from login class to main class?
or is there an other way to do something like this?
sorry for my poor english.
You should not try to pass an instance of SocketServer around. One of it's properties is context which means you should not used it outside the original context it was created in (i.e. activity it was created in) or you'll have memory leaks.
Your SocketServer class needs IP and port. This is the kind of information that you should pass between activities and then use that to create another instance of your SocketServer class.

Android Intent after onpostexecute fails to start

I have a registration system. The registration is working fine. My main problem is: I would like to start MainActivity.java after logging in. After sending the login data to the Server, the Server checks in Database if it matches and sends out an int (0 for unmatched) and (1 for success). This works great as well. But if i want to start the Intent after onPostExecute Method it gives out an Error:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult
...
This is my StartPage which exectues my AsyncTask Class. And receives success or unmatched in the Method getLoginMessage().
public class LoginPage extends Activity {
String userName;
String password;
String sendProtocolToServer;
static String matched = null;
static String unmatched;
static Context myCtx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginpage);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleLogin();
}
});
Button register = (Button) findViewById(R.id.registerBtn);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openMainActivityRegister = new Intent(
"com.example.fotosharing.REGISTERPAGE");
startActivity(openMainActivityRegister);
}
});
}
private void handleLogin() {
EditText editTextBox = (EditText) findViewById(R.id.EditTextUser);
EditText passwordTextBox = (EditText) findViewById(R.id.EditTextPassword);
userName = editTextBox.getText().toString();
password = passwordTextBox.getText().toString();
if (!userName.equals("") && !password.equals("")) {
sendProtocolToServer = "login" + "#" + userName + "#" + password;
ConnectToServer cts = new ConnectToServer(sendProtocolToServer);
cts.execute();
} else {
Toast.makeText(this, "Fill in Username and Password to login",
Toast.LENGTH_LONG).show();
}
}
public void getLoginMessage(String receivedMessage) {
if (receivedMessage.equals("success")) {
Intent openMainActivity = new Intent(
"com.example.fotosharing.TIMELINEACTIVITY");
openMainActivity.clone();
startActivity(openMainActivity);
}
if (receivedMessage.equals("unmatched")) {
Toast.makeText(this, "Password or username incorrect.", Toast.LENGTH_LONG).show();
}
}
}
This is my Async-Task class which receives Data from my Java-Server, and checks if it was an successful or an unmatched login. In onPostExecute im calling a Method in the LoginPage.class, which handles the Intent (here comes the Error).
public class ConnectToServer extends AsyncTask<Void, Void, String> {
public Context myCtx;
static Socket socket;
String sendStringToServer;
int protocolId = 0;
private static DataOutputStream DOS;
private static DataInputStream DIS;
StringBuffer line;
int j = 1;
String value;
static String res = null;
public ConnectToServer(String sendStringToServer) {
this.sendStringToServer = sendStringToServer;
}
public ConnectToServer(int i) {
this.protocolId = i;
}
public ConnectToServer() {
}
public ConnectToServer(Context ctx) {
this.myCtx = ctx;
}
protected String doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.1.106", 25578);
DOS = new DataOutputStream(socket.getOutputStream());
if (protocolId == 1) {
DOS.writeUTF("pictureload");
protocolId = 0;
} else {
DOS.writeUTF(sendStringToServer);
}
res = receive();
// DOS.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("RES: " + res);
return res;
}
public String receive() {
String receiveResult = null;
if (socket.isConnected()) {
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
DIS = new DataInputStream(socket.getInputStream());
int msg_received = DIS.readInt();
System.out.println("SERVER: " + msg_received);
if (msg_received == 1) {
receiveResult = "success";
System.out.println("IF (success): " + receiveResult);
}
if (msg_received == 0) {
receiveResult = "unmatched";
System.out.println("ELSE IF (unmatched): "
+ receiveResult);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// ***** return your accumulated StringBuffer as string, not current
// line.toString();
return receiveResult;
}
protected void onPostExecute(String result1) {
if (result1 != null) {
if (result1.equals("success") || result1.equals("unmatched")) {
sendToLoginPage(result1);
}
}
}
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
LoginPage lp = new LoginPage();
lp.getLoginMessage(result1);
}
}
This is the class I want to start when it was a successful login.
What am I doing wrong?
public class MainActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ActionBar actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
actionbar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#91d100")));
ActionBar.Tab Frag1Tab = actionbar.newTab().setText("Home");
ActionBar.Tab Frag2Tab = actionbar.newTab().setText("Share Photo");
Fragment Fragment1 = new TimelineActivity();
Fragment Fragment2 = new CameraActivity();
Frag1Tab.setTabListener(new MyTabsListener(Fragment1));
Frag2Tab.setTabListener(new MyTabsListener(Fragment2));
actionbar.addTab(Frag1Tab);
actionbar.addTab(Frag2Tab);
}
}
You cannot just create instance of your activity with new keyword, like this:
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
LoginPage lp = new LoginPage();
lp.getLoginMessage(result1);
}
This is wrong and it is probably why you are getting error. Code you posted is quite complex, so i am not sure if there are any other problems.
This is how it should be done:
So... Since you probably have ConnectToServer asyncTask in separate file, you need pass events or data to your LoginPage activity. For this purpose, you should use event listener, like this:
First, create interface that will represent communication between your ConnectToServer and your LoginPage.
public interface LoginResultListener {
public void getLoginMessage(String receivedMessage);
}
Now, make your LoginPage activity implement this interface:
public class LoginPage extends Activity implements LoginResultListener {
...
}
Now, update your ConnectToServer asyncTask, so that it uses LoginResultListener to communicate login result to your activity, like this:
public class ConnectToServer extends AsyncTask<Void, Void, String> {
private LoginResultListener listener;
...
public void setListener(LoginResultListener listener) {
this.listener = listener;
}
...
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
//THIS IS WHERE YOU DID WRONG
listener.getLoginMessage(result1);
}
...
}
Now finally, when you create new ConnectToServer async task from your activity, you need to set listener that will handle events when user logs in. Since you implemented this interface in your activity, you will send your activity object as listener parameter, see below:
ConnectToServer cts = new ConnectToServer(sendProtocolToServer);
// THIS IS IMPORTANT PART - 'this' refers to your LoginPage activity, that implements LoginResultListener interface
cts.setListener(this);
cts.execute();

Android update TextView with Handler

I am having problems with updating the TextView, I used the Handler method to pass the message to the UI. My application receives data(type integers) true io stream and shows in TextView.
My Activity class looks like this:
public class DeviceView extends Activity {
TextView dataX;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_view);
dataX = (TextView) findViewById(R.id.datax);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
dataX.setText(String.valueOf(msg.arg1));
}
};
}
}
I also have a separate class it extends Thread:
public class IOThread extends Thread {
public void run() {
byte[] buffer = new byte[1024];
int data;
while (true) {
try {
data = in.read(buffer);
Message message= Message.obtain();
message.arg1= data;
DeviceView.handler.sendMessage(message);
} catch (IOException ex) {
break;
}
}
}
}
Do I have to make a separate variable type String and point it to variable data and at last calling the count? Would that be enough to update TextView?
Can you try using an interface. Let the Activity implement it, pass it to the IOThread class. Once you get the result, pass the result to the Activity.
Interface named InterfaceData
public void getData(int data);
public class DeviceView extends Activity implements InterfaceData{
TextView dataX;
Handler handler;
IOThread ioThread;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_view);
handler = new Handler();
ioThread = new IOThread(this);
dataX = (TextView) findViewById(R.id.datax);
}
#Override
public void getData(int data){
handler.postDelayed(new Runnable(){
public void run(){
dataX.setText(data);
};
},100);
}
}
> Thread class
public class IOThread extends Thread {
InterfaceData interfaceData;
public IOThread(InterfaceData interfaceData){
this.interfaceData = interfaceData;
}
public void run() {
byte[] buffer = new byte[1024];
int data;
while (true) {
try {
data = in.read(buffer);
interfaceData.getData(data);
} catch (IOException ex) {
break;
}
}
}
}
I have found my problem it was not the Handler issue. THe code i posted at the beginning is coorect. The problem lyis on the way i read the received bytes[] array from the InputStream. I have tested by sending an integer int numbers = (int) 2 and when print this receivd data in terminal in Android app, it receivs only 1, even if i send int 3 or 4, i stil receive 1.
So i preceiated your example code #dcanh121 , but my question is actualy how do i read properly the integers that the server sends?
public void run() {
byte[] buffer = new byte[1024];
int data;
while (true) {
try {
data = in.read(buffer);
Log.d(TAG + data, "test");
Message message = Message.obtain();
message.arg1 = data;
Log.d(TAG + message.arg1, "test");
DeviceView.handler.sendMessageDelayed(message, 100);
} catch (IOException ex) {
Log.e(TAG_IOThread, "disconnected", ex);
break;
}
}
}

error: Only the original thread that created a view hierarchy can touch its views

Hi and thank you for looking at my question.
I am an intermediate programmer in C but an Android newbie. I have been trying to get a chat programming working. Assuming everything else in the code below works perfectly. The one question I like to ask is when I try to setText() from a thread running, I get an exception above. I looked at many many websites and here too. Found many things, but I really do not understand. Please explain to me in the most simple way or offer me some simple fix if possible.
Thank you very much!!
public class chatter extends Activity {
private String name = "Unknown User";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText msgToServer = (EditText) findViewById(R.id.msgBox);
final EditText chatFromServer = (EditText) findViewById(R.id.chatBox);
final Button MsgToServer = (Button) findViewById(R.id.sendButton);
Socket socket = null;
String ipAddress = "192.168.1.103";
try {
InetAddress serverAddr = InetAddress.getByName(ipAddress);
Socket socketMain = new Socket(serverAddr, 4444);
socket = socketMain;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "error", e);
}
final OutMsg outMsg = new OutMsg(socket);
Thread msgSenderThread = new Thread(outMsg);
msgSenderThread.start();
//chatFromServer.post(new InMsg(socket, chatFromServer));
Thread msgReceiverThread = new Thread(new InMsg(socket, chatFromServer));
msgReceiverThread.start();
MsgToServer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msgToServerString;
msgToServerString = msgToServer.getText().toString();
outMsg.message = name + ": " + msgToServerString;
outMsg.readyToSend = true;
msgToServer.setText("");
}
});
}
public void updateResultsInUi (String msg)
{
final EditText chatFromServer = (EditText) findViewById(R.id.chatBox);
chatFromServer.setText(msg);
}
public class InMsg implements Runnable {
Socket socket;
EditText chatFromServer;
public InMsg(Socket socket, EditText chatFromServer)
{
this.socket = socket;
this.chatFromServer = chatFromServer;
}
public void run(){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = "FIRSTMESSAGEFROMSERVER";
while (true)
{
if (str.equals("FIRSTMESSAGEFROMSERVER"))
str = in.readLine();
else
str = str + "\n" + in.readLine();
Log.e("TCP", "got the message: " + str);
//Here is where went wrong******************
chatFromServer.setText(str);
//******************************************
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "error in receiving", e);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.setNameMenu:
setname();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void populateChatBox (String msgFromS)
{
Log.e("TCP", "going in to popC");
final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
Log.e("TCP", " popC");
textNameInput.setText(msgFromS);
Log.e("TCP", "going out from popC");
}
public void setname()
{
setContentView(R.layout.custom_dialog);
final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
Button submitNameButton = (Button) findViewById(R.id.submitNameButton);
submitNameButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String nameinput = textNameInput.getText().toString();
if (!name.equals(""))
name = nameinput;
setContentView(R.layout.main);
}
});
}
}
In your run() method:
Message msg = new Message();
String textTochange = "text";
msg.obj = textTochange;
mHandler.sendMessage(msg);
Create the mHandler in your UI thread;
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (String)msg.obj;
//call setText here
}
};
You are not on the UI thread when setting the text. You need to be on UI if you want to work on UI items. Create a message handler on the UI thread, post your messages to it and call setText from the handler on the UI thread.
you can do this whenever you are in a thread:
msgToServer.post(new Runnable() {
public void run() {
msgToServer.setText("your text here");
}
}
Your problem is that there are certain interactions that you can only do on the UI thread. This is one of them.
Looks like you might want to use AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
Basically you could make your Runnable an AsyncTask instead and do the setText in onProgressUpdate, which gets run on the UIThread.
If you would like to use an AsyncTask to run in the background this is how I would do it:
public class UpdateTextProgress_Task extends AsyncTask<Void,String,Void> {
Socket socket;
EditText chatFromServer;
UpdateTextProgress_Task(EditText chatFromServer, Socket socket){
this.socket = socket;
this.chatFromServer = chatFromServer;
}
#Override
protected Void doInBackground(Void... params) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = "FIRSTMESSAGEFROMSERVER";
while(true){
if (str.equals("FIRSTMESSAGEFROMSERVER")){
str = in.readLine();
}
else{
str = str + "\n" + in.readLine();
}
Log.e("TCP", "got the message: " + str);
publishProgress(str); // calls the onProgressUpdate method
}catch (IOException e) {
Log.e("UpdateTextProgress", e.getMessage());
}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
chatFromServer.setText(progress[0]); //now we are on the UI thread so we can update our EditText
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.e("UpdateTextProgress", "Finished");
}
}
To execute the code:
UpdateTextProgress_Task task = new UpdateTextProgress_Task(chatFromServer,socket);
task.execute();

Categories

Resources