Locale returns locale without a country code

Viewed 1172

I need to get a country code from default Locale.

ConfigurationCompat.getLocales(context.resources.configuration).get(0)

It returns locale with language but the country is an empty string.

What is the reason? How do I get country code?

3 Answers

Use this to get country

String locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0).getCountry();
} else {
    locale = context.getResources().getConfiguration().locale.getCountry();
}

Note:- This is deprecated in API level 24

String locale = context.getResources().getConfiguration().locale.getCountry();

OR

//This will return country code from using his carrier network

TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();

Use This to get Country code:

    String locale;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        locale = context.getResources().getConfiguration().getLocales().get(0).getCountry();
    } else {
        locale = context.getResources().getConfiguration().locale.getCountry();
    }
Related