App crashing when fetching from string ressources [duplicate]

房东的猫 提交于 2019-12-12 21:37:13

问题


I have a string array in the string.xml ressources;

<string-array name="errors_signup">
    <item>Successful sign up</item>
    <item>Invalid username!\n(more than 4 characters have to be used)</item>
    <item>Username already taken!\n(Change it)</item>
    <item>Invalid e-mail address!</item>
    <item>E-mail already used!\n(Choose another one)</item>
    <item>Invalid password\n(more than 4 characters have to be used)</item>
    <item>Couldn\'t create the account!\n(try again)</item>
    <item>Passwords are not identical\n</item>
</string-array>

And I am trying to fetch it by the following code:

private String [] errorsSignup = getResources().getStringArray(R.array.errors_signup);

Running the above code immediately crashes the app. Any explanation? Here is the log:

05-06 02:22:18.941: D/dalvikvm(4111): GC_EXTERNAL_ALLOC freed 111K, 47% free 2913K/5447K, external 1033K/1036K, paused 63ms
05-06 02:22:19.066: W/dalvikvm(4111): threadid=1: thread exiting with uncaught exception (group=0x40018578)
05-06 02:22:19.073: E/AndroidRuntime(4111): FATAL EXCEPTION: main
05-06 02:22:19.073: E/AndroidRuntime(4111): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.CheesyDev.penpal/com.CheesyDev.penpal.A1_signup}: java.lang.NullPointerException

回答1:


Here what's wrong with the code above:

The resources of the Activity aren't available before the onCreate method gets called. So, trying to access the resources by initializing the string array when instantiating the Activity will throw an NPE.

The same issue is deeply explained here.

Thanks to @Rembo for this help!



来源:https://stackoverflow.com/questions/23484424/app-crashing-when-fetching-from-string-ressources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!