Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable is accessed within inner class. Needs to be declared final

Tags:

java

android

I'm getting a compilation error inside of my onClick.

Here's the code.

public class fieldsActivity extends Activity {  Button addSiteButton; Button cancelButton; Button signInButton;   /**  * Called when the activity is first created.  */ @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     // to create a custom title bar for activity window     requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);      setContentView(R.layout.fields);     // use custom layout title bar     getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);      Pager adapter = new Pager();     ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);     mPager.setAdapter(adapter);     mPager.setCurrentItem(1);        addSiteButton = (Button) findViewById(R.id.addSiteButton);     addSiteButton.setOnClickListener(new View.OnClickListener() {          @Override         public void onClick(View v) {            mPager.setCurrentItem(2, true); //Compilation error happens here.         }       });       cancelButton = (Button) findViewById(R.id.cancel_button);     signInButton = (Button) findViewById(R.id.sign_in_button);  } 
like image 885
PhDeOliveira Avatar asked Jan 20 '13 15:01

PhDeOliveira


People also ask

Is accessed from inner class needs to be declared final?

You can declare the variable final, or make it an instance (or global) variable. If you declare it final, you won't be able to change it later. Any variable defined in a method and accessed by an anonymous inner class must be final.

Can inner class access outer class variables Java?

Method Local inner classes can't use a local variable of the outer method until that local variable is not declared as final. For example, the following code generates a compiler error.

When to use final in Java?

You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final .

Can an inner class declared inside of a method access local variables of this method?

Yes, we can access the local final variables using the method local inner class because the final variables are stored on the heap and live as long as the method local inner class object may live.


1 Answers

If you don't want to make it final, you can always just make it a global variable.

like image 153
Kevin Zhao Avatar answered Oct 01 '22 19:10

Kevin Zhao