user2033281
user2033281

Reputation: 557

access integer anywhere outside method in same class

i declared a int jj in side onConfigurationChanged function now i want to acces it outside onConfigurationChangedanywhare in same class.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        final int jj=4;
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); 
        final int jj=2;   
    }
}

i want to i access this variable in same class like this:

public class MainActivity extends Activity {
    public static int aa=jj;
}

Upvotes: 0

Views: 125

Answers (2)

Thanos
Thanos

Reputation: 3665

Well, you could create a class to hold global variables:

public class GlobalVariables {
     public static int jj = 0;
}

Then you can access it from everywhere by simply calling GlobalVariables.jj

e.g.

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        GlobalVariables.jj=4;
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        GlobalVariables.jj=2;
    }

and

    public static int aa= 0;
    ...
    aa = GlobalVariables.jj;

However, I strongly agree with Simon. You need to study the basics of Object Oriented Design because what you ask breaks a couple of the OOD principles and my suggested solution is definitely an overkill.

Upvotes: 0

Simon
Simon

Reputation: 14472

Declare it as a class field. I don't know what you are doing with aa.

public class MainActivity extends Activity {

public int jj;

@Override
public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();

        jj=4;

    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();

        jj=2;

    }
}

}

It's clear from the question that you do not really understand the basics of programming, OOP and Java.

I recommend that you complete some basic tutorials before continuing until you understand primitives vs objects, final and static.

You should also understand you that cannot treat an Activity like a POJO.

Upvotes: 2

Related Questions