从字符串资源获取应用时崩溃 [英] App crashing when fetching from string ressources

查看:70
本文介绍了从字符串资源获取应用时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在string.xml ressources中有一个字符串数组;

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:

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

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.

此处深入解释了同一问题

感谢 @Rembo 获得此帮助!

这篇关于从字符串资源获取应用时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆