'How to auto get my country currency symbol with out mentioning the country in kotlin android studio
I am using this code but it return usd=$ instead of pkr=Rs I wanted to get Rs without mention my country or currency
val currency: Currency = Currency.getInstance(Locale.getDefault())
val symbol: String = currency.symbol
Solution 1:[1]
As I know, It will work using your device telephony manager.
Here is the working code, You gave to get the county code.
fun Context.getDeviceCountryCode(): String {
var countryCode: String?
val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
countryCode = tm.simCountryIso
if (countryCode != null && countryCode.length == 2) return countryCode.lowercase()
countryCode = if (tm.phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
getCDMACountryIso()
} else {
tm.networkCountryIso
}
if (countryCode != null && countryCode.length == 2) return countryCode.lowercase()
countryCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
resources.configuration.locales[0].country
} else {
resources.configuration.locale.country
}
return if (countryCode.length == 2) countryCode.lowercase() else "us"
}
After that call this method for getting the currency symbol
fun getCurrencySymbol(currencyCode: String?): String? {
val currencySymbol: String?
if (currencyCode == null || currencyCode.isEmpty()) {
currencySymbol = currencyCode
} else {
val currencyLocale: Locale?
val currencyLocaleMap: Map<Currency?, Locale>?
val currency: Currency?
try {
currency = Currency.getInstance(currencyCode)
currencyLocaleMap = getCurrencyLocaleMap()
currencyLocale = currencyLocaleMap[currency]
} catch (e: java.lang.Exception) {
return "$"
}
currencySymbol = if (currency != null && currencyLocale != null) {
currency.getSymbol(currencyLocaleMap[currency])
} else {
currencyCode
}
}
return currencySymbol
}
Here are the calling methods, you can call that method and the method will be return the currency code, According to your device.
countryCurrencySysmbol = getCurrencyIcon(getDeviceCountryCode())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mehul Boghra |
