-1

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?

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Alexandre
  • 1,259
  • 2
  • 15
  • 25
  • When you are comparing Strings, use always the method equals instead of ==, because == compares the memory reference, and "equals" compares the value. So, you should do currentLocale.getLanguage().toString().equals("fr") – programmer23 Feb 20 '15 at 12:43
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Sergey Glotov Feb 20 '15 at 12:43
  • Hi programmer23, Thank you for your answer, it's totally what I was looking for. – Alexandre Feb 20 '15 at 13:46

3 Answers3

1

If you are comparing non-primitive datatypes use the equals method for comparison.

AngularLover
  • 364
  • 1
  • 12
0

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();
        }
QArea
  • 4,955
  • 1
  • 12
  • 22
0

String comparison is a common scenario of using both == and equals method. Since java.lang.String class override equals method, It return true if two String object contains same content but == will only return true if two references are pointing to same object.

Nauman Afzaal
  • 1,046
  • 12
  • 20