Search code examples
androidif-statementlocale

Android app Locale variable comparison with String


I'm currently trying to test (with an if statement) the value of the current Locale variable.

but the result returned (by checking in Debug mode) is false.

This is the code I'm using:

Locale frLocale = new Locale("fr");
Locale usLocale = new Locale("en");
Locale currentLocale = Locale.getDefault();

Toast.makeText(this, frLocale.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, usLocale.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, currentLocale.getLanguage().toString(), Toast.LENGTH_SHORT).show();

if (currentLocale.getLanguage().toString() == "fr") {
     currentLocale.setDefault(usLocale);
     Toast.makeText(this, "Toto", Toast.LENGTH_SHORT).show();
     Toast.makeText(this, currentLocale.getLanguage().toString(), Toast.LENGTH_SHORT).show();
}

The Toasts are there to help me check (without debug mode) what are the values returned.

I'm surprised because:

  1. currentLocale.getLanguage().toString() of my if returns "fr"

Do you see something wrong with my way of doing?


Solution

  • Try the following solution:

    private static final LOCATE_TEXT="fr";
    
    Locale frLocale = new Locale(LOCATE_TEXT);
    Locale usLocale = new Locale("en");
    Locale currentLocale = Locale.getDefault();
    
    Toast.makeText(this, frLocale.toString(), Toast.LENGTH_SHORT).show();
            Toast.makeText(this, usLocale.toString(), Toast.LENGTH_SHORT).show();
            Toast.makeText(this, currentLocale.getLanguage().toString(), Toast.LENGTH_SHORT).show();
    if(currentLocale.getLanguage().toString().equals(LOCATE_TEXT)){
                currentLocale.setDefault(usLocale);
                Toast.makeText(this, "Toto", Toast.LENGTH_SHORT).show();
                Toast.makeText(this, currentLocale.getLanguage().toString(), Toast.LENGTH_SHORT).show();
            }