0

Am trying to fetch data from API using Retrofit and show in a spinner but it is throwing an error "java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference"

Below is My MainActivity Class

     spinnerCode = findViewById(R.id.spinner_code);

       UserNumber userNumber = ApiClient.getRetrofit().create(UserNumber.class);


 Call<List<CountryCodes>> call = userNumber.countryCode();

    call.enqueue(new Callback<List<CountryCodes>>() {

        List<CountryCodes> data=new ArrayList<>();

        @Override
        public void onResponse(Call<List<CountryCodes>> listCall, Response<List<CountryCodes>> response) {

             data = response.body();

            for(int i=0;i<data.size();i++){
              String  item = data.get(i).getCountry_Name();
                List<String> listSpinner = new ArrayList<String>();
                listSpinner.add(item);

                ArrayAdapter adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item,listSpinner);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerCode.setAdapter(adapter);

            }

        }


        @Override
        public void onFailure(Call<List<CountryCodes>> call, Throwable t) {

        }
    });

This is My Model Response Class

public class CountryCodes {

    public String Country_Name;
    public String CountryCode;

    public String getCountry_Name() {
        return Country_Name;
    }

    public void setCountry_Name(String country_Name) {
        Country_Name = country_Name;
    }

    public String getCountryCode() {
        return CountryCode;
    }

    public void setCountryCode(String countryCode) {
        CountryCode = countryCode;
    }
}

This is My Interface Class

 @POST("List_All_Available_Countries")
    Call<List<CountryCodes>>  countryCode();
Community
  • 1
  • 1
najam
  • 67
  • 1
  • 10

1 Answers1

1

You got this error because , List need to be initiated before call the method data.size() .

//So Add this line in your MainActivity

List<CountryCodes> data=new ArrayList<>();

//then add value into it.
 @Override
 public void onResponse(Call<List<CountryCodes>> listCall, Response<List<CountryCodes>> response) {

       data = response.body();}
            
androidLearner
  • 1,534
  • 1
  • 6
  • 13