Reputation: 91
In my program, a boolean value (called metronomeOn) is supposed to be set to true at the click of one button, and false at the click of a different button. The only class I have (MainActivity) implements Runnable. So after the thread gets started, in the run method, depending on the value of metronomeOn, it's supposed to execute a block of code. My problem is that after the onClick method from the button that is supposed to set metronomeOn to true, metronomeOn's value isn't changed.
ButtonListeners (The method is called in onCreate):
public void ButtonListeners() {
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
metronomeOn = true;
}
});
bStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentBeatIndex = 1;
tvCurrentBeatIndex.setText("");
metronomeOn = false;
}
});
}
The run method:
if (metronomeOn) {
tvBpm.setText("IN IF STATEMENT");
//other code...
}
I have absolutely no idea why metronomeOn isn't switching values. I know that the run method gets executed, and metronomeOn is only ever changed in onCreate and onDestroy. Any ideas why this isn't working? Thanks in advance!!
EDIT**************************** I've gotten rid of the run method and the implementation of the Runnable class, so there is no problem there, yet metronomeOn still always returns false.
EDIT AGAIN************************ I have no idea why or how, but after deleting the Runnable stuff and restarting Eclipse, it now works. MetronomeOn changes value! Thank you to everyone who gave advice!
Upvotes: 1
Views: 1044
Reputation: 3337
Multiple possible reasons:
volatile
? If a variable is used across threads, you should mark it.Runnable
does not cause a thread to spawn. And you can call the run method directly without a thread.From the little parts we get to see of your Application, I think you probably want to use Services instead of Threads/Runnables? Services can get started and stopped, run independently of the Activity and may also spawn threads.
As you cannot access the activity from a service, you may do your debug output with the Android logging methods in the Log
class.
Upvotes: 1
Reputation: 893
Can't figure out the exact problm, but do try it the other way round. Name them method1
and method2
, and use as--
public void method1(View v) {
\\code for button1
}
public void method2(View v) {
\\code for button2
}
And use in xml for respective buttons:
android:onClick="method1"
android:onClick="method2"
Upvotes: 0