java.lang.NullPointerException while referencing string variable in code

前端 未结 2 1462
执念已碎
执念已碎 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.

提交回复
热议问题