0

I am reading a inputstream chunck by chunk and tryng to set read chunk to a textview from a Thread class but text is only getting printed after completion of while loop below is my code :

class SendFileThread  extends Thread 
{

    Handler mHandler;
    FileInputStream instream;

    SendFileThread(Handler h, FileInputStream stream )
    {
        mHandler = h;
        instream = stream;
        this.setPriority(Thread.MAX_PRIORITY);
    }

    @Override
    public void run()
    {
 final StringBuilder result = new StringBuilder();
        Message msg;
        byte [] usbdata = new byte[64];
         int readcount = 0;         
        sendByteCount = 0;
        int val = 0;

        if(instream != null)
        {
            try
            {
                readcount = instream.read(usbdata,0,64);
            }
            catch (IOException e){e.printStackTrace();}

            while(readcount > 0)
            {   

                    sendData(readcount, usbdata);
                    sendByteCount += readcount;
                try
                {
                    readcount = instream.read(usbdata,0,64);
                     if(readcount == -1){
                            pending = false;
                            //send_file = false;
                            setDefaultsBoo("pending",pending, J2xxHyperTerm.this);
                        }else{
                             result.append(new String(usbdata, 0, readcount));
                        }

                     runOnUiThread(new Runnable() {

                         @Override
                         public void run() {
                                 readText.setMovementMethod(new ScrollingMovementMethod());
                                    readText.setText(result.toString());
                                    //scrollView.smoothScrollTo(0, readText.getHeight() + 30);

                        }
                    });

                }
                catch (IOException e){e.printStackTrace();}

            }
        }
            }
}

text is getting set to textview only after all the work is done.

Smart
  • 71
  • 1
  • 2
  • Views can be touched by only the thread which creates it. TextView is created by main thread, so you can not update/change state from another thread(as in your case above). However you can send an event from thread to use Handler/Looper.getMainLooper/RunOnUiThread(if in Activity context) , so that Main thread will update the TextView. – Lavakush Apr 11 '16 at 08:48

4 Answers4

1

Hi you can use this method in your thread :

 runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       //update your textview
                    }
                });
abdoulayeYATERA
  • 209
  • 1
  • 2
0

After work is done, try this -

Message msg = Message.obtain(handler, what, arg1, arg2, "text");
// what= some int identififer, lets say 1101
msg.sendToTarget();

in the listening activity implement Handler.Callback. You will have to implement handleMessage

@Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
case 1104: // the what identifier you set in  message
String text = (String) msg.obj;
textView.setText(text)
break;
}
return false;
}
crashOveride
  • 839
  • 6
  • 12
0

You could use an AsyncTask for this use-case, as the ability to update views on the UI thread is included right out of the box.

http://developer.android.com/reference/android/os/AsyncTask.html

This is from the usage example provided, with comments to show you where the main thread action happens.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

     // Done in the background, on a separate thread
     protected Long doInBackground(URL... urls) {

         int count = urls.length;

         long totalSize = 0;

         for (int i = 0; i < count; i++) {

             totalSize += Downloader.downloadFile(urls[i]);

             // This part of the loop publishes the progress to onProgressUpdate(..)
             publishProgress((int) ((i / (float) count) * 100));

             if (isCancelled()) break;
         }
         return totalSize;
     }

     // Called on the main thread whenever publishProgress(..) is called
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     // Also called on the main thread, after the background task is finished
     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
MattMatt
  • 2,242
  • 33
  • 30
0

You could use an EventBus, to communicate between your thread to your activity. This is their github project. you can implement it and also enable communication between every Android app component. For example, like in your case, between thread and activity.

Nir Rauch
  • 21
  • 12