setText is not working inside a while loop
Asked Answered
K

2

-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..

Kunz answered 8/5, 2015 at 16:29 Comment(5)
Is that actual code? I mean, what changes flag so that loop ends?Cabana
@Cabana when is back button pressed, flag is set to false.Kunz
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 SSCCEAthos
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());Laugh
because you are blocking the main thread.Donia
A
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();
             }
         });
     }

}
Amberly answered 8/5, 2015 at 16:47 Comment(1)
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.Amberly
B
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);
Butcher answered 8/5, 2015 at 16:47 Comment(1)
possibly if (!flag), though, as apparently that's the exit conditionDonia

© 2022 - 2024 — McMap. All rights reserved.