java.lang.NullPointerException while referencing string variable in code

前端 未结 2 1461
执念已碎
执念已碎 2021-01-25 06:52

I\'m trying to reference a few strings that I\'ve stored in an xml. I\'m getting this error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual         


        
相关标签:
2条回答
  • 2021-01-25 07:47
    private String CLIENT_ID = getString(R.string.MY_CLIENT_ID);
    

    If you initialize the field on class initialization, you are calling getString() before onCreate(), and thus the Context has not initialized. Better use it like this

    public void onCreate(final Bundle bundle) {
        // Other code    
        CLIENT_ID = getString(R.string.MY_CLIENT_ID);
    }
    

    Also I strongly advise against caching the strings, because you can get wrong translations if the language has changed (this problem already happened to me so I say this from experience). Instead, use getString() whenever you need it.

    0 讨论(0)
  • 2021-01-25 07:52

    You need a Context to access your app resources. You're trying to get a resource without having a valid context first. Move your calls to onCreate() method, where your Activity is first created and you have the context:

    private String CLIENT_ID;
    private String CLIENT_SECRET;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        temp = (TextView) findViewById(R.id.temp);
        CLIENT_ID = getString(R.string.MY_CLIENT_ID);
        CLIENT_SECRET = getString(R.string.MY_CLIENT_SECRET);
    
        obj = new foo(CLIENT_ID, CLIENT_SECRET, this);
        obj.bar()
    }
    
    0 讨论(0)
提交回复
热议问题