Search code examples
javaandroidarrayslocale

Locale.getLanguage() equalize to String


I'm trying to make an android app with multiple languages. I have a string array. What i am trying to do is make this array for multiple languages. For example; I have an array in English like "Mercury, Venus, Earth, Mars". Also i have an array in Turkish like "Merkür, Venüs, Dünya, Mars". I'm learning device's main language with "Locale" property and i can show that language. But what i want to do is show the language array depends on the device's main language.

As i said, i have two array. I tried to learn device's language and equlize the string array. But i can't equlize them because of .equals parameter. It didn't work.

String[] TurkishPlanetNames ={"Merkür", "Venüs", "Dünya", "Mars", "Jüpiter", "Satürn", "Uranüs", "Neptün"};

String[] PlanetNames ={"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};

Locale locale = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0);

if (locale.getLanguage().equals("en-US")){

        Toast.makeText(getApplicationContext(), "It worked!", Toast.LENGTH_LONG).show();

    } else {
        Toast.makeText(getApplicationContext(), "It didn't work!", Toast.LENGTH_LONG).show();
    }

So, how can i equalize the device's language and a string like "en-US". .equals - .compareTo - .contentEquals - .matches are doesn't work.


Solution

  • locale.getLanguage(); would return just "en" no matter what version of English your device uses (British/American).

    The following call will return the string in the format you're trying to use in your .equals();

    Locale.getDefault().toString(); //e.g. returns "en_US"
    

    but make sure you use the underscore instead of the hyphen.

    Alternatively, use the method you're currently using as follows:

    if (locale.getLanguage().equals(new Locale("en").getLanguage())) {
        //...
    }
    

    (source)