Harsh Shah
Harsh Shah

Reputation: 2332

Locale is returning empty string in Android

I am developing one android app and I need to do a certain change based on user's Locale country (region).

I found an official link and I tried to get a Locale but it's returning me an empty string.

Here is the code I tried but I am getting all the string as an empty string:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String localeCountry = LocaleList.getDefault().get(0).getDisplayCountry();
            String localeISO3Country = LocaleList.getDefault().get(0).getISO3Country();
            String locale = getResources().getConfiguration().getLocales().get(0).getCountry();
            String locale1 = getResources().getConfiguration().getLocales().get(0).getDisplayCountry();
            String locale2 = getResources().getConfiguration().getLocales().get(0).getDisplayVariant();
        }else {
            Locale current = getResources().getConfiguration().locale;
            String currentCc = getResources().getConfiguration().locale.getCountry();
            String iso3Country = getResources().getConfiguration().locale.getISO3Country();
            String cCode = Locale.getDefault().getCountry(); 
        }

I tried the toString() method also but it is returning me the only language but as per the documentation it should have returned values including language and country.

Here is my code:

String toString = getResources().getConfiguration().getLocales().toString();
in Log it printed only language: 
[en] 

Am I missing something?

Upvotes: 3

Views: 2474

Answers (2)

Waged
Waged

Reputation: 420

i find that this is a working workaround for me .. may be it could help..

String lCode = Locale.getDefault().getLanguage();
String cCode = Locale.getDefault().getCountry();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        Locale deviceLocales = Resources.getSystem().getConfiguration().getLocales().get(0);
        lCode = deviceLocales.getLanguage();
        cCode = deviceLocales.getCountry();
        String serverCode = lCode+"-"+cCode;
        Log.e(UserAPI.TAG,"Bigger Than Nougat code "+serverCode);
  }

Upvotes: 1

Sunny
Sunny

Reputation: 68

I am too late for answering this but I am posting my answer so it might be helpful to others.

As per documentation if your country language doesn't support then your locale.toString method will be returning the null or empty string.

Here is the official site link

Upvotes: 2

Related Questions