Issue
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
Solution
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.
Answered By - codeMagic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.