Machlev Development
Machlev Development

Reputation: 47

Android - Can't access int from onCreate() method

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.

Upvotes: 1

Views: 976

Answers (3)

maclir
maclir

Reputation: 3309

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

    ...
}

Upvotes: 2

Umer Farooq
Umer Farooq

Reputation: 7486

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 ++;
    ..........
}

Upvotes: 1

Tarsem Singh
Tarsem Singh

Reputation: 14199

Declare int maxInt; before onCreate() but inside class

and change your code

final int maxInt = Integer.parseInt(max);

to

maxInt = Integer.parseInt(max);

Upvotes: 1

Related Questions