1

I have the following int:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    setContentView(R.layout.activity_score);
    // Show the Up button in the action bar.
    setupActionBar();
    Intent i = getIntent();
    String max = i.getStringExtra(MainActivity.EXTRA_MAX);
    final int maxInt = Integer.parseInt(max);

And i want to access it from here:

public void plus1 (View V)
{
    maxInt ++;
}

But i get an error, even when not using final, When the int is inside the class:

public class ScoreActivity extends Activity {

I get a crash.

1
  • What is the stack trace of the crash? It might be caused by an entirely different problem. Commented Jul 14, 2013 at 16:22

3 Answers 3

2

Your app crashing because the variable maxInt in plus1 is undefined. maxInt's scope is local to onCreate. Also final variables are like constant variables in C. They can only get a value when you initialize them, meaning you can't change their value.

Your maxInt should not be final and should be a global variable:

public class ScoreActivity extends Activity {

    int maxInt;

    protected void onCreate(Bundle savedInstanceState) { 
        ...
        maxInt = Integer.parseInt(max);
        ...
    }

    public void plus1 (View V) {
        maxInt ++;
    }

    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

Declare int maxInt; before onCreate() but inside class

and change your code

final int maxInt = Integer.parseInt(max);

to

maxInt = Integer.parseInt(max);

Comments

1

The reason you can't access maxInt in another method is because you created it in onCreate method. Its scope is local to that method so it isn't visible to rest of the class. Moreover, once OnCreate() goes out of scope, maxInt will be destroyed and the data stored in it will be lost.

If you want to access an object/variable all over the class, make it global.

int maxInt;

protected void onCreate(Bundle savedInstanceState) { 

    maxInt = Integer.parseInt(max);
...
....
}

public void plus1 (View V) {
  .....   
  maxInt ++;
    ..........
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.