0

I am trying to use a String from the string.xml file as a key in a key-value pair. However when I try to declare the variable before the onCreate() method, the program crashes. So if I use the following code I get an error:

    public class MainActivity extends ActionBarActivity {
        String MAX_SQUAT = getResources().getString(R.string.max_squat);
        protected void onCreate(Bundle savedInstanceState) {
        //blah blah blah
    }
    }

Whereas when I declare MAX_SQUAT inside the onCreate() method, there is no problem. I want to declare it outside of onCreate() method so I don't need to define it in other methods

2
  • Please add the code and the crash's stack trace Commented May 27, 2015 at 20:16
  • Sorry, was a little too fast to hit enter. Some code added now. Commented May 27, 2015 at 20:22

1 Answer 1

3

You need a Context to get resources (as you can see in the Docs getResources() is a method of Context). Since the Context isn't available before onCreate(), you can't do this.

You can declare the variable before onCreate() but you can't initialize it until after onCreate() has been called.

Ex.

public class MainActivity extends ActionBarActivity {

    String MAX_SQUAT;

    protected void onCreate(Bundle savedInstanceState) {
        // super call, set content view
        // now you can get the string from strings.xml safely
        MAX_SQUAT = getResources().getString(R.string.max_squat);
    }

Declaring it as a member variable this way but initializing it in onCreate() will allow you to use it throughout the class and keep it from crashing.

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

1 Comment

That'll do it. Thanks!

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.