moe
moe

Reputation: 11

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();
  });}

Upvotes: 1

Views: 1870

Answers (1)

phlogratos
phlogratos

Reputation: 13924

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);
}

Upvotes: 1

Related Questions