سؤال

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
هل كانت مفيدة؟

المحلول

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!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top