android处理程序使变量成为最终

时间:2011-07-02 16:25:34

标签: java android variables handler final

为什么我在编写处理程序时会收到此消息并且编译器坚持将变量作为最终变量?

Cannot refer to a non-final variable inside an inner class defined in a different 
method

我的问题是如何在我的代码中定义一个非final变量:(如何将书籍,文件,注释和时间更改为非终结)它们是全局变量,我将它们传递给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();
  });}

1 个答案:

答案 0 :(得分:1)

您必须将 book file note Time 声明为final,因为您在其中使用它们匿名内部类。

我想你不希望它们成为最终版,因为你想改变它们的价值观。这可以通过使用额外的最终变量来实现。如果您想更改图书的价值,可以写下:

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