NullPointerException trying to access a String resource

冷暖自知 提交于 2019-12-01 16:14:16

问题


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?


回答1:


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);
...



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/4157228/nullpointerexception-trying-to-access-a-string-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!