Issue
I made two timers. At some point one of them is increasing and other one is decreasing. I made two integers to increase/decrease every second and use setText
for TextView
. But for some reason it's not updating. I printed out integers and code was working but text isn't changing for TextView
. Here's my code:
TextView timerone, timertwo;
int turn = 1;
int timerOne = 20;
int timerTwo = 20;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begin_after);
timerone = findViewById(R.id.timerone);
timertwo = findViewById(R.id.timertwo);
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
Thread counterThread=new Thread(()->{
try{
while(true){
if(turn % 2 == 0) {
timerOne++;
timerTwo--;
}else{
timerOne--;
timerTwo++;
}
Thread.sleep(1000);
}
}catch (Exception e){
}
});
counterThread.start();
}
Solution
Try this solution
Thread counterThread=new Thread(()->{
try{
while(true){
if(turn % 2 == 0) {
timerOne++;
timerTwo--;
}else{
timerOne--;
timerTwo++;
}
// Here you will be updating textview's
runOnUiThread(new Runnable() {
@Override
public void run() {
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
}
});
Thread.sleep(1000);
}
}catch (Exception e){
}
});
counterThread.start();
Answered By - Ammar Abdullah
Answer Checked By - David Goodson (JavaFixing Volunteer)