0

There is an annoying problem guys, take a look at this code:

   textView.setText("hi");
   SystemClock.sleep(5000);
   textView2.setText("hi");

When you run this code logically text view must show "hi" and 5 seconds later text view 2 show "hi". But this doesn't happen and after 5 seconds both of them together show this word!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Mehrdad
  • 1
  • 1
  • 4
    Possible duplicate of [How to call a method after a delay in Android](https://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android) – KeLiuyue Oct 14 '17 at 17:12

1 Answers1

0

You are blocking the main application thread and preventing the UI from being updated. This is covered in any decent book on Android app development.

Replace your code with this:

textView.setText("hi");
textView2.postDelayed(new Runnable() {
  public void run() {
     textView2.setText("hi");
  }
}, 5000);
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • This can fix my problem but i want to use delay in for loop and this kind of delay can not be use full. – Mehrdad Oct 14 '17 at 15:09
  • @Mehrdad: There is nothing about `postDelayed()` that prevents it from being used for periodic UI updates within an activity or fragment. [This sample app](https://github.com/commonsguy/cw-omnibus/tree/v8.7/Threads/PostDelayed) displays a `Toast` every five seconds, using `postDelayed()`. – CommonsWare Oct 14 '17 at 15:13
  • yea it use for toast but if u can show an example with for loop :) – Mehrdad Oct 14 '17 at 15:17
  • @Mehrdad: Sorry, you cannot do what you want with a `for` loop, other than calling `postDelayed()` on each pass of the `for` loop, with progressively longer delays... and I don't know how well that will work, particularly for lots of loop passes. – CommonsWare Oct 14 '17 at 15:23