简体   繁体   中英

Better way to get static content from resources in android?

I have written a class named DateUtils where I tried to get resource in a static field like this way

    public class DateUtils{
    private static String value;

    public static string getValue(Context context){
            if (value== null) {
            value= context.getResources().getString(R.string.my_value);
            }
            return value; }
    }

But I found an answer How can I get a resource content from a static context? where they created an application class and get the reference of this application class to assign value for static field.

In this way the downside is that there is no guarantee that the non-static onCreate() will have been called before some static initialization code tries to fetch your Context object. That means your calling code will need to be ready to deal with null values which sort of defeats the whole point of this question Reference Static way to get 'Context' on Android?

My question is which one is better approach to initialize static field?

My question is which one is better approach to initialize static field?

Neither. Get rid of the static field.

Your application needs to handle the case where the user changes their language while your process is still running. You need to retrieve this string resource at more appropriate points, so that when you undergo the configuration change, you start using the right string. As it stands, with your implementation (no matter how you populate the static field), you will never change the language of this string, and therefore the string will be wrong in some cases.

And if the answer is "this string is never being translated", get rid of the string resource and put the string in the Java code as a final static field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM