Issue
I am trying to localize my app. Therefore, I moved all strings to strings.xml. Then, I replace all hard-coded text in my code with string variables. However, I get a runtime error whenever I try to assign the resource values to my string variables.
My code looks like this:
public class MainActivity extends AppCompatActivity {
private final String MSG_STATUS =
this.getResources().getString(R.string.status);
...
}
The strings.xml looks like this:
<resources>
<string name="status">My Status</string>
</resources>
This lead to the following error:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.xxx/com.xxx.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
All examples I have found so far had a very similar approach. Thus, I'm confused why it's not working. I guess it might have to do with the context.
Solution
Because you can't access the resources until the Activity is initialized- in onCreate, after calling super. Before then it isn't set up properly. The this pointer also won't work until the constructor has been called, and can't be used to statically initialize variables.
Basically, move all the code to onCreate.
Answered By - Gabe Sechan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.