I'm trying to figure out threading and have this issue where a TextView stops being updated if the app is sent to the back, and then restored.
How can I ensure that the TextView continues to be updated after the app is brought back to the front?
Or...
How do I reconnect the TextView to the handler in my run-nable thread after restarting the activity?
There is a Progress Bar which works just fine, so I'm somewhat confused. I'd appreciate some advice as I think I may be making a simple mistake.
public class ThreadTestActivity extends Activity {
private Handler handler;
private static ProgressBar progress;
private TextView tv;
private int counter = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ThreadTest);
handler = new Handler();
progress = (ProgressBar) findViewById(R.id.progressBar1);
tv = (TextView) findViewById(R.id.myText);
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
thread_fun();
});}
}
private void thread_fun() {
new Thread(new Runnable() {
public void run() {
try {
while (counter < 100) {
counter += 20;
Thread.sleep(2000);
// Update the progress bar and TextView (in 5 chunks of 20, 0 to 100)
// This works perfectly it the app stays in front
handler.post(new Runnable() {
public void run() {
// but after sending to the back (esc) and bringing the activity back to the front
progress.setProgress(counter); //This progres bar maintains its value and updates correctly
tv.setText(String.valueOf(counter)); //This TextView reverts to its default text and does not update
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}