Reputation: 123
I have created a counter app that counts from 0 to infinity until the loop is stopped using a stop button. The app contains 2 buttons(start and stop) and 1 textview. I aim to display the values from 0 to infinity(until the loop is stopped) in the textview. I am using a while loop.
For example, the count value starts from 0 so the while loop starts from 0 and continues until the loop is terminated using the stop button. I want to display values in real time in the textview.
public class MainActivity extends AppCompatActivity {
boolean start;
int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt1=findViewById(R.id.button);
Button bt2=findViewById(R.id.button2);
TextView tv=findViewById(R.id.textView);
Handler h=new Handler(getApplicationContext().getMainLooper());
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start=true;
new Thread(new Runnable() {
@Override
public void run() {
while(start){
count=count+1;
}
h.post(new Runnable() {
@Override
public void run() {
tv.setText(" "+count);
}
});
}
}).start();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start=false;
}
});
}
}
The code above is not displaying values in real-time in the textview. What's the issue? Also, should I use a handler or runonUIThread for such tasks?
Help will be appreciated!
Upvotes: 0
Views: 44
Reputation: 3154
You should use runOnUiThread
, since the while
loop is blocking the UI thread.
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(" "+count);
}
});
here's the refactored code to get this working.
public class MainActivity extends AppCompatActivity {
boolean start;
int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt1=findViewById(R.id.button);
Button bt2=findViewById(R.id.button2);
TextView tv=findViewById(R.id.textView);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start=true;
new Thread(new Runnable() {
@Override
public void run() {
while(start){
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(" "+count);
}
});
count++;
}
}
}).start();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start=false;
}
});
}
}
Upvotes: 0