This is my code that receive country code by input(in onCreate()
method):
countryCodeEdt = (EditText)findViewById(R.id.register_country_code_tv);
countryCodeEdt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String newCode = s.toString();
System.out.println("this is new code value "+newCode);
if (newCode == null || newCode.length() < 1){
pickupCountryTv.setText("Choose a country");
}
else {
if (countryMaps.containsKey(newCode)){
countryCode = newCode;
countryName = countryMaps.get(newCode);
pickupCountryTv.setText(countryName);
}
else{
countryCode = "";
countryName = "";
pickupCountryTv.setText("Wrong country code");
}
}
}
});
Now I want to pre-select the country code automatically without input by people. I found the answer using TelephonyManager. But I'm confusing of how to set up for my countryCodeEdt
variable to get the value from this method:
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;
}
Can someone give me some suggestion? Thanks in advance.