0

I want to get all languages using this code:

public List<String> getGeneratePreferedLanguagesList()
    {
        String[] languageCodes = Locale.getISOLanguages();
        List<String> list = new ArrayList<>();

        for (String cc : languageCodes)
        {
            list.add(new Locale("", cc).getDisplayLanguage());
        }

        Collections.sort(list);

        return list;
    }

But the final list is empty. Do you know where I'm wrong?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • 1
    So your `Locale.getISOLanguages()` already returns an empty result? – Zabuzard Mar 11 '18 at 21:45
  • Please provide a [mcve]. – shmosel Mar 11 '18 at 21:48
  • 1
    Just tested. Actually your list **is not empty**. It contains many elements. It's just that your `String`s are all empty due to `getDisplayLanguage()`. You can easily debug such stuff by placing small `System.out.println(...)` in your code. – Zabuzard Mar 11 '18 at 21:50

2 Answers2

4

You should't pass an empty string as first argument, you should pass the language.

In your current language.

Locale locale = new Locale(cc);
list.add(locale.getDisplayLanguage());

In its own language.

Locale locale = new Locale(cc);
list.add(locale.getDisplayLanguage(locale));

Modify that line and you should check always the the javadoc. https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html#Locale(java.lang.String)

Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34
3

I assume that by "the final list is empty" you mean that the list contains all empty stings. If that's what's happening, it's because you are using the wrong Locale constructor. Try:

list.add(new Locale(cc).getDisplayLanguage());

To display each language in it's own language, you can try this:

Locale locale = new Locale(cc);
list.add(locale.getDisplayLanguage(locale));
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521