0

I'm trying to get the country name where the phone is in. For instance if the user is in Germany it has to say Germany. I've tried several things to make this happen, but I haven't found any proper solution. I know I can use TelephonyManager, but that will give me the ISO, and I want the name of the country. I've also tried this getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();, but that always gives me "United States" even though I'm not there. I know this is possible as I've seen it in another application. Should I use the ISO somehow to accomplish what I what, or is there a smarter/easier way?

Please, don't vote this post as duplicate as I've already searched here on Stackoverflow, but there isn't any solution to get the name of the country :)

ada dudu
  • 49
  • 1
  • 2
  • 8

1 Answers1

0

Where am I? - Get country gives this code

/**
 * Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
 * @param context Context reference to get the TelephonyManager instance from
 * @return country code or null
 */
public static String getUserCountry(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US);
        }
        else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US);
            }
        }
    }
    catch (Exception e) { }
    return null;
}
Community
  • 1
  • 1
James Russo
  • 578
  • 3
  • 18
  • Hmmm, wouldn't that be too "deep"? I mean to get the country name. Can't I use the ISO to get the name? `getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();` gave me "United States", I just want it to work properly (if it's possible) – ada dudu Aug 01 '16 at 21:09
  • are you testing `getApplicationContext().getResources().getConfiguration().locale.getDisplayCoun‌​try();` on the android emulator or an actual phone? – James Russo Aug 01 '16 at 21:11
  • It gives me the ISO just with lowercase :( – ada dudu Aug 01 '16 at 22:07
  • `Locale loc = new Locale("","NL"); loc.getDisplayCountry();` @adadudu can get country name from ISO so just call that on ISO – James Russo Aug 01 '16 at 22:29
  • I don't understand :( – ada dudu Aug 01 '16 at 22:37
  • @adadudu get the ISO from my method, then create a new Locale object using that string and get it's country by calling `getDisplayCountry()` on that new Locale object initialized with the countries ISO – James Russo Aug 02 '16 at 14:01