gpt4 book ai didi

android - 奇怪的 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 08:57:02 24 4
gpt4 key购买 nike

我有一个奇怪的问题...

我的文件 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

在{我实例化 building_name 的行}

我的代码有什么问题?请帮忙

最佳答案

在您的 Activity 初始化之前,您不能调用 getString。这是因为 getStringcontext.getResources().getString() 相同。并且上下文未初始化。

所以基本上,你不能用这种方式给静态变量赋值。

但是有一种方法可以在静态变量中使用资源字符串。为此,请创建您的应用程序(请参阅 thisthis ),然后从那里检索上下文。这是一个简短的例子:

<manifest ...>
...
<application android:name="com.mypackage.MyApplication" ... >
...
</application>
...
</manifest>

然后创建MyApplication.java文件:

public class MyApplication extends Application 
{
private static MyApplication s_instance;

public MyApplication ()
{
s_instance = this;
}

public static Context getContext()
{
return s_instance;
}

public static String getString(int resId)
{
return getContext().getString(resId);
}
}

然后用它来获取字符串资源:

private final String BUILDING_NAME = MyApplication.getString(R.string.building_name);

您甚至可以在静态字段中执行此操作。

关于android - 奇怪的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6261990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com