1

I am building an Android application. The application is pulling data from a server and should update a TextView live with that data. Here is my code for the process with unnecessary details left out:

public class MainActivity 
{

Starting the Runnable from the OnCreate class:

    protected void OnCreate(...)
    {
    ...
    Thread connect = new Thread(runnable);
    connect.start();
    }

Code for the Runnable class:

    Runnable runnable = new Runnable()
    {
        public void run()
        {
        ...(setting up server input stuff)
        final TextView strDisplay = (TextView)findViewById(R.id.stringDisplay);
            while (!Thread.currentThread ().isInterrupted())
            {
                try
                {
                    final String serverInput = subscriber.recvStr(); //receiving server input
                    strDisplay.post(new Runnable()
                    {
                        public void run()
                        {
                            //Updating TextView "strDisplay" with the latest server data
                            strDisplay.setText(serverInput);
                        }
                     });
                 }
                 catch...
             }
         }
     };
}

However, when I run this, only the first server input it receives is displayed in the TextView and then although more input is coming in (It is, I checked with Log), the TextView does not update. In the console, I read "onFinishInput" after it prints the first input and then the stream of input starts on the console. I thought starting a new Runnable would allow it to update, but it hasn't done anything.

AreM
  • 97
  • 10
  • I am not sure if you are calling this but from here, it looks like you are not calling runnable.run(); – Eugene H Jul 22 '15 at 21:05

2 Answers2

1

The UserInterface can only be updated by the UI Thread. You need a Handler, to post to the UI Thread:

Android update TextView in Thread and Runnable

Community
  • 1
  • 1
StephenG
  • 2,851
  • 1
  • 16
  • 36
0

It turns out that this code that I posted does in fact work. The key part was:

`strDisplay.post(new Runnable()
{
    public void run()
    {
        //Updating TextView "strDisplay" with the latest server data
        strDisplay.setText(serverInput);
    }
});`

I might have had another error in my program, but this is what I currently have and it's working beautifully :-) I hope this helps someone out!

AreM
  • 97
  • 10