androidandroid-studiospinnermobile-country-code

Cannot read country code selected in a spinner Android


I am working on an app in which users have to select a country code, i was successful in creating a spinner for the said purpose as shown in this link:
Creating a spinner for choosing country code But i am getting problem in reading the value selected in the spinner.

{
               String abc = onCountryPickerClick();//abc is always null 
}  
    public String onCountryPickerClick (){
         ccp.setOnCountryChangeListener(new CountryCodePicker.OnCountryChangeListener() {
             @Override
             public void onCountrySelected() {
                 selected_country_code = ccp.getSelectedCountryCodeWithPlus();
             }

         });
         return  selected_country_code;
    }

Solution

  • When String abc = onCountryPickerClick(); is being invoked, the selected_country_code value will be assigned to abc.

    When your CountryCodePicker.OnCountryChangeListener's onCountrySelected() method is being invoked, the ccp.getSelectedCountryCodeWithPlus();'s value gets assigned to selected_country_code. Since String is immutable, changing selected_country_code's value won't change the value of abc, nor the return selected_country_code; will be invoked.

    One of possible solutions would be to change your CountryCodePicker.OnCountryChangeListener anonymous implementation to assign the selected country value to abc e.g.

    @Override
    public void onCountrySelected() {
           selected_country_code = ccp.getSelectedCountryCodeWithPlus();
           abc = selected_country_code
    }