0

I have an AsyncTask extended class that listens to a port in the background.

My problem is that when I try to add the text that I receive from the socket into a TextView on the UI, the app stops because I'm doing it from outside of the activity thread. What do I need to do to my class to be able to edit the TextView?

Here is the code:

public class Receive_String extends AsyncTask<Void, Void, Void> {                  
    @Override
    protected Void doInBackground(Void... params) { 
            try {
            TextView text_ShowString=(TextView)findViewById(R.id.textView_ShowString);

            ServerSocket conn = new ServerSocket(35316);            
            Socket listen=conn.accept();
            BufferedReader input = new BufferedReader(new InputStreamReader(listen.getInputStream()));
            String message = input.readLine();

            text_Notificari.append(message);

            conn.close();
            } catch (IOException e) {
            e.printStackTrace();}               
        }
        return null;
    }

}
Rami
  • 7,879
  • 12
  • 36
  • 66
user3605321
  • 45
  • 1
  • 10

2 Answers2

1

Move your update-the-UI code to onPostExecute() of your AsyncTask.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
1

Update in onPostExecute(). If you continously reading from port and want to make changes in main UI do it in onProgressUpdate() .

Eg : Make text_ShowString and message global

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);    
    text_ShowString.setText(message);  
}  
sujithvm
  • 2,351
  • 3
  • 15
  • 16