SetText does not work inside while loop

why?

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

getCpuInfo returns a string if I try to write this method, return to the log, there is everything that should be, but nothing happens with the text.

-2
java android settext
source share
2 answers

This will not work ... the display will be updated after the completion of your function. try it

 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(); } }); } } 
+3
source share

An infinite loop in the ui thread is probably not a good idea. setText schedule the operation of drawing, placing in the queue of threads ui. Unfortunately, the same thread is busy with the loop. You can use the internal TextView handler to publish Runnable to the ui thread queue. For example.

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

and instead of your while loop you just do

 outCPU.post(mRunnable); 
+2
source share

All Articles