Search code examples
androidtextviewdatainputstream

TextView remains the same it doesnt get set to any new value


I'm facing a problem,On a button press i try to read the DataInputstream which has data coming in and display the data.

I'm using a while loop to read the data. But the dynamic update of the Textview doesnt happen.

TextView datatextview = (TextView)findViewById(R.id.data); 

DataInputStream Din = new DataInputStream(socket.getInputStream());
Button getData= (Button)findViewById(R.id.getdata);
getData.setOnClickListener(new OnClickListener() {
    public void onClick(View v) { 
    //.......stuff .......
    try{
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    int bytesRead = -1;
    String message1 = "";
    while (true) {
        message1 = "";
        data = Din.readLine();
        bytesRead = (reading).length();
        if (bytesRead != -1) {
            Log.v(TAG,"data"+data); //I'm getting the data correctly
            //But not able to update it in the TextView :(
            datatextview.setText(data);  //doesnt work
        }
    }

Solution

  • You have to exit your method and relinquish control of the UI thread in order for your views to update. You should probably be using AsyncTask with its progress updating functionality to do this, so that you're not hogging the UI thread.

    Something like:

    public class MyTask extends AsyncTask<Void, String, Void> {
      private final TextView progress;
    
      public MyTask(TextView progress) {
        this.progress = progress;
      }
    
      @Override
      protected void onPreExecute() {
        progress.setText("Starting...");
      }
    
      @Override
      protected Void doInBackground(Void... unused) {
        ... your buffer code, including publishProgress(data); in your while loop ...
      }
    
      @Override    
      protected void onProgressUpdate(String... data) {
        progress.setText(data[0]);
        progress.invalidate(); // not sure if this is necessary or not
      }
    
      @Override
      protected void onPostExecute(Void unused) {
        progress.setText("Finished!");
      }
    }
    

    Then you can create and execute your AsyncTask using:

    new MyTask(datatextview).execute();
    

    Edit - make sure to use @Override which helps alert you if your method signatures are not correct.