奇怪的空指针异常
我有奇怪的问题...
我的文件 strings.xml 包含:
<?xml version="1.0" encoding="utf-8?>
<resources>
<string name="building_name">My House</string>
</resources>
嗯,我的 R 包含:
[...]
public static final class String {
public static final int building_name=0x7f02383;
}
[...]
所以,当我尝试在我的代码中调用这个字符串时,如下所示:
private final String BUILDING_NAME = getString(R.string.building_name);
我有这个错误:
java.lang.RuntimeException: Unable to instanciate activity ComponentInfo{...}: java.lang.NullPointerException
{...}
caused by: java.lang.NullPointerException
在 {the line where I instanciate thebuilding_name}
我的代码有什么问题吗?请帮忙
I have strange problem...
My file strings.xml contains:
<?xml version="1.0" encoding="utf-8?>
<resources>
<string name="building_name">My House</string>
</resources>
Well, my R contains:
[...]
public static final class String {
public static final int building_name=0x7f02383;
}
[...]
So, when I try to call this String in my code like this:
private final String BUILDING_NAME = getString(R.string.building_name);
I have this error:
java.lang.RuntimeException: Unable to instanciate activity ComponentInfo{...}: java.lang.NullPointerException
{...}
caused by: java.lang.NullPointerException
at {the line where I instanciate the building_name}
What's wrong with my code?Please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Activity 初始化之前,您无法调用
getString
。这是因为getString
与context.getResources().getString()
相同。并且上下文未初始化。所以基本上,你不能以这种方式给静态变量赋值。
但是有一种方法可以在静态变量中使用资源字符串。为此,创建您的应用程序(请参阅此和this),然后从那里检索上下文。这是一个简短的示例:
然后创建 MyApplication.java 文件:
然后使用它来获取字符串资源:
您甚至可以对静态字段执行此操作。
You can't call
getString
before your Activity has been initialized. That's becausegetString
is the same ascontext.getResources().getString()
. And context is not initialized.So basically, you can not assign value to static variables in this way.
But there is a way to use resource strings in your static variables. For this create your application (see this and this) and then retrieve context from there. Here is a short example:
Then create
MyApplication.java
file:And then use it to get string resource:
You can even do this fir static fields.
使用这个可能对你有帮助
这对我有用
Using this might help you
This works for me
在某些情况下会发生这种情况,同样您应该尝试下面提到的一些步骤:
There are some cases where this happens, for the same you should try some steps mentioned below:
如果您在从一项活动获取某些文本到另一项活动时出现错误
例如
getString 给出空指针异常,那么
StudentID 是 String 类型,因此只需将 StudentID 声明为
private String StudentID;
if you have error in getting some text from one activity to another activity
Like for example
getString giving null pointer exception then
that StudentID is of String type so just declare StudentID as
private String StudentID;