3

I have implemented localization in my android application but I have a small issue. I am not being able to retrieve the default value of a string from default strings.xml file. for eg. inside project/res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
        <string name="distance">distance</string>
</resources>

and inside project/res/values-nl/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <string name="distance">afstand</string>
</resources>

My requirement is to get the value of 'distance' variable from project/res/values/strings.xml file regardless of which locale is currently in use.

Dipendra
  • 1,547
  • 19
  • 33
  • What actually is your problem? – G_S Dec 11 '12 at 15:42
  • getApplicationContext().getString(R.string.distance) retrieves value as "distance" when english locale is used and "afstand" when dutch locale is use. But I want the value as "distance" regardless of the locale currently in use. – Dipendra Dec 11 '12 at 15:54
  • Then dont mention it as afstand and mention it as distance in the dutch locale – G_S Dec 11 '12 at 15:59
  • nope, I cant do that. I need it for some other purpose too. thank you anyways – Dipendra Dec 11 '12 at 16:13
  • @Dipendra - You could try this http://stackoverflow.com/questions/14984659/android-strings-xml-in-various-languages-scenario – Braj Oct 14 '15 at 06:09

1 Answers1

0

We can do it with context config and it will work from API +17 like:

public static String getDefaultString(Context context, @StringRes int stringId){
        Resources resources = context.getResources();
        Configuration configuration = new Configuration(resources.getConfiguration());
        Locale defaultLocale = new Locale("en"); // default locale
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList localeList = new LocaleList(defaultLocale);
            configuration.setLocales(localeList);
            return context.createConfigurationContext(configuration).getString(stringId);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            configuration.setLocale(defaultLocale);
            return context.createConfigurationContext(configuration).getString(stringId);
        }
        return context.getString(stringId);
    }

For earlier versions of Android, you could use something like that:

public static String getDefaultString(Context context, @StringRes int stringId){
  Resources resources = context.getResources();
  Locale defaultLocale = new Locale("en");// default locale
  configuration.locale = newLocale;
  resources.updateConfiguration(configuration, res.getDisplayMetrics());
  return resources.getString();
}

But I guess it can change the current context in the app. And if you don't use the default language in the app, there will be a problem with localization.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Djek-Grif
  • 1,391
  • 18
  • 18