I’m feeling very, very stupid right now… I feel like I must be missing something really obvious.
I’ve encountered variations of this problem on multiple occasions now, however here is my current example –
When the activity is created, there will be a button marked Start and text set to –:– next to it. I would like to have it so that when the button is pressed, a timer starts from one minute and displays the seconds remaining in the –:– text as 00:59 etc. etc., and the text on the button changes to Pause. If the button is pressed when the timer is running, it pauses the timer and changes the text on the button to Start.
So I was using a boolean, timerRunning, in order to keep track of whether the timer was running or not. But if I try to change timerRunning within the onClickListener it gives an error and tells me to change timerRunning to final, and then once I do that it says “The final local variable timerRunning cannot be assigned, since it is defined in an enclosing type.”
I’m sorry if this is unclear – I’m just really confused with where I should be declaring variables / how to access them etc. in Android, I don’t really understand why I keep getting weird errors all the time.
Thanks.
public class Timing extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timing);
Button bStartJammer = (Button) findViewById(R.id.buttonStartJammer);
CountDownTimer cdtJammerTimer;
long lJammerTotalMS = 60000;
final boolean timerRunning = false;
bStartJammer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
timerRunning = true;
}
});
}
}
Without source context, it’s tough to visualize what you’re doing.
How are you defining your click handler? If it’s an anonymous class, you’ll run into the
finalissues–is your activity or handler so complex that it makes a separate class completely necessary?In the previous question my click handler was implemented by the activity, so it has access to that instance’s variables. A much-abbreviated skeleton of what I had been doing before not using the
CountDownTimer:(I took a bunch of stuff out, and added some really early code back in, so it’s a bit of a mish-mosh, but the ideas are there.)