-2

why is that?

while (flag) {
outCPU.setText(getCpuInfo());
}

getCpuInfo returns string, if I try to write this method's return out into a log, there is everything that should be, but nothing happens to textview..

andrew
  • 183
  • 1
  • 2
  • 12
  • Is that actual code? I mean, what changes `flag` so that loop ends? – DSlomer64 May 08 '15 at 16:33
  • @DSlomer64 when is back button pressed, flag is set to false. – andrew May 08 '15 at 16:39
  • 2
    How can such a question receive an upvote? As long as you don't provide more information, noone can seriously help you. Please post an [SSCCE](http://www.sscce.org/) – SME_Dev May 08 '15 at 16:40
  • 3
    You're starting an endless loop in the UI thread, and thus prevent it from doing what it's supposed to do: react to UI events and repaint the UI. Why would you need a loop? Just use `outCPU.setText(getCpuInfo());` – JB Nizet May 08 '15 at 16:42
  • because you are blocking the main thread. – njzk2 May 08 '15 at 16:47

2 Answers2

3

It will not work... display will update after your function finishes. Try this

boolean flag;
private void updateTextView(){
     outCPU.setText(getCpuInfo());
     if(flag){
         outCPU.post(new Runnable(){
             public void run(){
                 updateTextView();
             }
         });
     }
}

private void your_function(){
    if(flag){
         outCPU.post(new Runnable(){
             public void run(){
                 updateTextView();
             }
         });
     }

}
sabbir
  • 438
  • 3
  • 11
  • Why you need loop? updateTextView() function works like a loop. You need to set the flag variables from another place. If you do not need to log just set the flag to false. If you need to log, call updateTextView function again with flag set to true at first. – sabbir May 09 '15 at 04:22
2

The infinite loop on the ui thread it is not probably a good idea. setText schedule a draw operation, posting on the ui thread queue. Unfortunately the same thread is busy looping. You could use the TextView's internal handler to post a Runnable on the ui thread's queue. E.g.

private Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
        if (!flag) {
            outCPU.removeCallbacks(this);
            return;
        }
        outCPU.setText(getCpuInfo());
        outCPU.postDelayed(this, 200);
    }
};

and in place of your while loop you simply do

outCPU.post(mRunnable);
Blackbelt
  • 156,034
  • 29
  • 297
  • 305