【问题标题】:ttempt to invoke interface method'java.util.Iterator java.util.List.iterator()' on a null object reference, fetching data in Spinner with Retrofit [closed]尝试在空对象引用上调用接口方法 java.util.Iterator java.util.List.iterator()',使用 Retrofit 在 Spinner 中获取数据 [关闭]
【发布时间】:2021-05-18 13:56:12
【问题描述】:

我正在尝试使用 Retrofit 从 API 获取数据并在微调器中显示,但它抛出错误“java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator() ' 在空对象引用上"

下面是我的 MainActivity 类

     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) {

        }
    });

这是我的模型响应类

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;
    }
}

这是我的接口类

 @POST("List_All_Available_Countries")
    Call<List<CountryCodes>>  countryCode();

【问题讨论】:

标签: java android android-studio android-spinner


【解决方案1】:

您收到此错误是因为,需要在调用方法 data.size() 之前启动 List。

//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();}
            

【讨论】:

  • 但它仍然显示相同的错误
  • ""//然后添加价值。"如何 ?请帮助我
  • 在添加值之前,你检查列表的大小了吗?它应该返回 0 作为列表大小。
  • for(int i=0;i
  • 是错误在循环中。要确保列表已启动,请检查循环前的大小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 2018-11-20
  • 2019-06-26
  • 1970-01-01
相关资源
最近更新 更多