Shishdem Shishdem - 23 days ago 9
Android Question

Final variable from resources file

I have an activity with some final variables. I extracted their values (let's assume they're all Strings) into a resources file.

The problem:

If I directly assign them on the instantiation (as following):

private final String PREFERENCE_NAME = getResources().getString(R.string.preference_name);


I get the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference


I understand the problem; the onCreate() method has not been called yet which means I cannot access context-related methods (
getResources()
).

If I want to assign the value in the onCreate() method of the activity, I get the error
Cannot assign value to final variable 'PREFERENCE_NAME'


The question is: How can I get my final variables to be assigned from the resources file? And if this is not possible, what is the best practice for a solution?

Thanks in advance.

Answer

In this case I think the best thing to do it just make multiple calls to the resources. You still only have to change the value in one place and the call to getResources() isn't an expensive one.

Comments