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
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.
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()
}