从字符串资源获取时应用程序崩溃

时间:2014-05-06 01:11:06

标签: android android-resources

我在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>

我试图通过以下代码获取它:

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

运行上面的代码会立即崩溃应用程序。任何解释? 这是日志:

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 个答案:

答案 0 :(得分:1)

上面的代码出了什么问题:

调用Activity方法之前onCreate的资源不可用。因此,在实例化string array时通过初始化Activity来尝试访问资源会抛出NPE。

同样的问题得到了深刻解释here

感谢@Rembo获得此帮助!