NullPointerException 尝试访问 String 资源

发布于 2024-10-02 02:51:30 字数 321 浏览 2 评论 0原文

我有以下 /res/values/uris.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="bladder">blahblah</string>
</resources>

我正在代码中访问它:

private String bladderUrl= getString(R.string.bladder);

但它返回 null。我不知道为什么?

I have the following /res/values/uris.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="bladder">blahblah</string>
</resources>

I am accessing it in code:

private String bladderUrl= getString(R.string.bladder);

But it is returning null. I'm not sure why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

メ斷腸人バ 2024-10-09 02:51:30

我猜你像这样放置了膀胱网址:

public class YourActivity extends Activity {
    private String bladderUrl = getString(R.string.bladder);

    @Override
    public void onCreate(Bundle savedInstanceState) {

...

但是你需要这样做:

public class YourActivity extends Activity {
    private String bladderUrl;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        bladderUrl = getString(R.string.bladder);
...

My guess you placed bladderUrl smth like this:

public class YourActivity extends Activity {
    private String bladderUrl = getString(R.string.bladder);

    @Override
    public void onCreate(Bundle savedInstanceState) {

...

However you need to do smth like this:

public class YourActivity extends Activity {
    private String bladderUrl;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        bladderUrl = getString(R.string.bladder);
...
诺曦 2024-10-09 02:51:30

首先要弄清楚这一点。您不必必须将所有字符串都放在strings.xml中。时期。

伊曼纽尔的回答部分正确。当上下文初始化时,您必须在 onCreate() 方法中获取该字符串。他的回答只是部分正确,因为他还提到你必须将字符串放在 strings.xml 中,这是不正确的。

First of all to clear that up. You don't have to have all your strings in strings.xml. Period.

Emmanuels answer is partially right. You have to get the string inside your onCreate() method when the context is initialized. His answer is only partially correct since he also mentioned that you have to have the strings inside the strings.xml which is not true.

忆离笙 2024-10-09 02:51:30

首先,确保这些值位于文件 strings.xml 中。

此外,您无法从构造函数访问字符串。应用程序上下文尚未初始化。您应该在 onCreate() 中执行此操作。

以马内利

First, make sure these values are in the file strings.xml.

Also, you can't access the strings from the constructor. The application context is not yet initialized. You should do it in onCreate().

Emmanuel

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文