2

In Android Studio, I have an integer.xml file where I define two integers. min and max. If I set min to 8, how do I get this value and set it to a static in Java?

Something like:

private static final int MIN = getInteger(R.integer.min);

I know this works very differently from getting strings using R.id.string.

No matter what I try, I'm getting errors about static and non-static methods.

2 Answers 2

2

You cannot initialize a final static variable this way. Final static variable must be initialized at the place of declaration or in static {} block, i.e. before any instance of the class has been created. However, resources are not static. So you can't use this.getResources().getInteger() to initialize it: getResources() method requires a Context which is not initialized at that time.

One solution is to initialize the variable directly:

static final int MIN = 8;

Alternatively, you can make it non-static and initialize in onCreate().

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

Comments

1

To access getInteger method you need an instance of resource first. You generally can do that via getResources method of the Context class (Activity, Service, etc..). So to access a context instance in static declaration, you need to get a static reference to the context, that generally is a bad idea, leading to memory leaks. I would suggest to declare such constants without using resources, just in code. If you have some specific reasons to keep these constants in resources, retain a reference to application and use it as intended.

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.