-2

I'm very new to Java programming and I'm having troubles with while loops in Threads. I post here an example where I use the while loop.

public class MainActivity extends AppCompatActivity {

private boolean running = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView text = (TextView)findViewById(R.id.textView);

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (running) {

                try{Thread.sleep(1000);} 
                catch(InterruptedException e){}

                running = false;
                text.setText("false!");

                running = true;

                try{Thread.sleep(1000);}
                catch(InterruptedException e){}

                text.setText("True!");
            }
        }
    }).start();
}
}

When running is set to false, the Thread doesn't run and the app does not show anything. When running is set to true, the app crashes after text.setText("false!");

Thank you all in advance!

Jens
  • 5,767
  • 5
  • 54
  • 69
  • 1
    Read the exception message ( and post it in your question too). It should tell you, you can't update UI outside of the UI thread – AxelH May 08 '17 at 11:54
  • Look into the logcat and post the stacktrace – Jens May 08 '17 at 11:55
  • This [answer](http://stackoverflow.com/a/5185140/4391450) is the simplest to use – AxelH May 08 '17 at 11:57
  • Android is the wrong platform to learn Java threads, IMO. Try a desktop app – OneCricketeer May 08 '17 at 12:00
  • thread sleeps your UI, meaning you cannot update UI during that time. either use Handler or Looper or an AsyncTask to update UI after your background action @Jens – Yashika May 08 '17 at 12:02
  • you can't update UI in background Thread. You need to update UI in Main thread. For this you can use: runOnUiThread(new Runnable() { @Override public void run() { //your code goes here } }); – Gurvinder Rajpal May 08 '17 at 12:09
  • Thank you all very much! I just didn't know this thing! sorry, i'm just a beginner :) – Jacopo Trapani May 08 '17 at 16:29

1 Answers1

0

you cannot access textView from thread, you can only change view objects from main thread

Reflection
  • 399
  • 2
  • 11