Skip to content Skip to sidebar Skip to footer

Settext Is Not Working Inside A While Loop

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, b

Solution 1:

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();
             }
         });
     }

}

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

privateRunnablemRunnable=newRunnable() {
    @Overridepublicvoidrun() {
        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);

Post a Comment for "Settext Is Not Working Inside A While Loop"