how to get string from different locales in Android?

AndroidLocaleAndroid Resources

Android Problem Overview


So I want to get the value of a String in several locales regardless of the current locale setting of the device/app. How should I do that?

Basically what I need is a function getString(int id, String locale) rather than getString(int id)

How could I do that?

Thanks

Android Solutions


Solution 1 - Android

NOTE If your minimum API is 17+, go straight to the bottom of this answer. Otherwise, read on...

NOTE If you are using App Bundles, you need to make sure you either disable language splitting or install the different language dynamically. See https://stackoverflow.com/a/51054393 for this. If you don't do this, it will always use the fallback.

If you have various res folders for different locales, you can do something like this:

Configuration conf = getResources().getConfiguration();
conf.locale = new Locale("pl");
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Resources resources = new Resources(getAssets(), metrics, conf);
String str = resources.getString(id);

Alternatively, you can just restart your activity using the method pointed to by @jyotiprakash.

NOTE Calling the Resources constructor like this changes something internally in Android. You will have to invoke the constructor with your original locale to get things back the way they were.

EDIT A slightly different (and somewhat cleaner) recipe for retrieving resources from a specific locale is:

Resources res = getResources();
Configuration conf = res.getConfiguration();
Locale savedLocale = conf.locale;
conf.locale = desiredLocale; // whatever you want here
res.updateConfiguration(conf, null); // second arg null means don't change

// retrieve resources from desired locale
String str = res.getString(id);

// restore original locale
conf.locale = savedLocale;
res.updateConfiguration(conf, null);

As of API level 17, you should use conf.setLocale() instead of directly setting conf.locale. This will correctly update the configuration's layout direction if you happen to be switching between right-to-left and left-to-right locales. (Layout direction was introduced in 17.)

There's no point in creating a new Configuration object (as @Nulano suggests in a comment) because calling updateConfiguration is going to change the original configuration obtained by calling res.getConfiguration().

I would hesitate to bundle this up into a getString(int id, String locale) method if you're going to be loading several string resources for a locale. Changing locales (using either recipe) calls for the framework to do a lot of work rebinding all the resources. It's much better to update locales once, retrieve everything you need, and then set the locale back.

EDIT (Thanks to @Mygod):

If your minimum API level is 17+, there's a much better approach, as shown in this answer on another thread. For instance, you can create multiple Resource objects, one for each locale you need, with:

@NonNull Resources getLocalizedResources(Context context, Locale desiredLocale) {
    Configuration conf = context.getResources().getConfiguration();
    conf = new Configuration(conf);
    conf.setLocale(desiredLocale);
    Context localizedContext = context.createConfigurationContext(conf);
    return localizedContext.getResources();
}

Then just retrieve the resources you like from the localized Resource object returned by this method. There's no need to reset anything once you've retrieved the resources.

Solution 2 - Android

Here is a combined version of the approaches described by Ted Hopp. This way, the code works for any Android version:

public static String getLocaleStringResource(Locale requestedLocale, int resourceId, Context context) {
    String result;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // use latest api
        Configuration config = new Configuration(context.getResources().getConfiguration());
        config.setLocale(requestedLocale);
        result = context.createConfigurationContext(config).getText(resourceId).toString();
    }
    else { // support older android versions
        Resources resources = context.getResources();
        Configuration conf = resources.getConfiguration();
        Locale savedLocale = conf.locale;
        conf.locale = requestedLocale;
        resources.updateConfiguration(conf, null);

        // retrieve resources from desired locale
        result = resources.getString(resourceId);

        // restore original locale
        conf.locale = savedLocale;
        resources.updateConfiguration(conf, null);
    }

    return result;
}

Usage example:

String englishName = getLocaleStringResource(new Locale("en"), R.string.name, context);

Note

As already stated in the original answer, it might be more efficient to replace multiple call of the above code with a single configuration change and multiple resources.getString() calls.

Solution 3 - Android

Based on the above answers which awesome but a little complex. try this simple function:

public String getResStringLanguage(int id, String lang){
    //Get default locale to back it
    Resources res = getResources();
    Configuration conf = res.getConfiguration();
    Locale savedLocale = conf.locale;
    //Retrieve resources from desired locale
    Configuration confAr = getResources().getConfiguration();
    confAr.locale = new Locale(lang);
    DisplayMetrics metrics = new DisplayMetrics();
    Resources resources = new Resources(getAssets(), metrics, confAr);
    //Get string which you want
    String string = resources.getString(id);
    //Restore default locale
    conf.locale = savedLocale;
    res.updateConfiguration(conf, null);
    //return the string that you want
    return string;
}

Then simply call it: String str = getResStringLanguage(R.string.any_string, "en");

Happy code :)

Solution 4 - Android

place this Kotlin extension function into your code and use it like this:

getLocaleStringResource(Locale.ENGLISH,R.string.app_name)

fun Context.getLocaleStringResource(
requestedLocale: Locale?,
resourceId: Int,
): String {
val result: String
val config =
    Configuration(resources.configuration)
config.setLocale(requestedLocale)
result = createConfigurationContext(config).getText(resourceId).toString()

return result
}

Solution 5 - Android

object Language {

    var locale: Locale? = null



    fun getLocaleStringResource(
        resourceId: Int,
        requestedLocale: Locale? = locale,
    ): String = with(game.activity) { Configuration(resources.configuration).run {
        setLocale(requestedLocale)
        createConfigurationContext(this).getText(resourceId).toString()
    } }

}

Solution 6 - Android

Could this be done by for example?

String stringFormat = getString(stringId);
String string = String.format(Locale.ENGLISH, stringFormat, 6);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncheng yangView Question on Stackoverflow
Solution 1 - AndroidTed HoppView Answer on Stackoverflow
Solution 2 - AndroidJohnson_145View Answer on Stackoverflow
Solution 3 - AndroidAmr JyniatView Answer on Stackoverflow
Solution 4 - AndroidUsama Saeed USView Answer on Stackoverflow
Solution 5 - AndroidВладислав ШестернинView Answer on Stackoverflow
Solution 6 - AndroidAlexView Answer on Stackoverflow