android handler making variable as final
Why do I get this message when I'm writing a handler and the compiler insist on making the variable as final?
Cannot refer to开发者_运维知识库 a non-final variable inside an inner class defined in a different
method
My question is how can I define a non-final variable in my code: (how can I change book, file, note and time to non finals) they are global variables and I'm passing them to trakingNotes
public void trakingNotes (final double book, final long file, final String note, final double Time) {
MaxInfo = 100;
Timer updateTimer = new Timer("NoteSaveings");
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateGUI( book, file, note, Time);
}
}, 0, 1000);
}
NotesDB dbnotes = new NotesDB(this);
private void updateGUI( final double book, final long file, final String note, final double Time) {
long idy;
// Update the GUI
noteHandler.post(new Runnable() {
public void run() {
long idy;
dbnotes.open();
idy= dbnotes.insertnoteTitle (book, file, note, Time);
if ((book) == samebook )//samebook is a global varible
{ReadDBnotes();}
dbnote.close();
});}
You have to declare book, file, note and Time as final because you use them inside of anonymous inner classes.
I guess you don't want them to be final because you want to change their values. This can be accomplished by using additional final variables. If you want to change the value of book you can write this:
public void trakingNotes (double book, final long file, final String note, final double Time) {
MaxInfo = 100;
Timer updateTimer = new Timer("NoteSaveings");
final double changedBook = book + 1.0;
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateGUI( changedBook, file, note, Time);
}
}, 0, 1000);
}
精彩评论