When I press the button once, the while loop stops, and the message is displayed, but when I press it again, the while loop will not start again (I know this because the message in the runnable is not displayed).
Also, the combination while(!boo) in the thread and a boo=true; in the button does not produce any result.
What might I be doing wrong? I put Boolean boo=true; outside onCreate, so I don’t think that is the problem…
public class UiTester extends Activity {
protected static final String TAG = null;
String s="";
Button stopper;
TextView display3;
//Boolean boo=true;
int n=0;
public Boolean boo=true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
on=(Button) findViewById(R.id.bon);
off=(Button) findViewById(R.id.boff);
display=(TextView) findViewById(R.id.tvdisplay);
display3=(TextView) findViewById(R.id.tvdisplay3);
stopper=(Button) findViewById(R.id.stops);
final Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
n++;
display3.setText("System On"+n);
}
};
stopper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(boo==true)
{
boo=false;
display3.setText("System Off");
}
else{
boo=true;
}
}
});
Thread x = new Thread() {
public void run() {
while (boo) {
handler.post(updater);
//non UI elements can go here
try {
Log.d(TAG, "local Thread sleeping");
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
};
x.start();
}
}
When boo is false your thread just ends. It will not start over again.