为什么方法返回list <country>的零大小

时间:2018-11-29 19:37:57

标签: java android list

我有这段代码可从API获取信息

public class MainModel implements InterfacesSpace.MAIN_MODEL {

List<CountryModel> ARRAYS;



 @Override
public List<CountryModel> Weather_Information() {

    final Call<CountryModel.ResultModel> connection = INSTANCE_API_SERVICE.loadItems();
    connection.enqueue(new Callback<CountryModel.ResultModel>() {
        @Override
        public void onResponse(Call<CountryModel.ResultModel> call, Response<CountryModel.ResultModel> response) {

            countryModels = response.body().getCountryModels();

            for (int i = 0; i < countryModels.size(); i++) {


                CountryModel ye = new CountryModel("","","");
                ye.setCountry(countryModels.get(i).getCountry());
                ye.setCity(countryModels.get(i).getCity());
                ye.setDegree(countryModels.get(i).getDegree());
                ARRAYS.add(ye);
                //Log.e("TESTSAIF" ,ARRAYS.get(0).getCity());

                //  Log.e("array size ", String.valueOf(ARRAYS.size()));
                //  Log.e("Size", String.valueOf(arrayList.size()));
            }

        }

        @Override
        public void onFailure(Call<CountryModel.ResultModel> call, Throwable t) {
            Log.e("error",t.getMessage());
        }

    });

  //  return ARRAYS.get(0);


    return ARRAYS;

}

以及在我的演示师课程中

 @Override
public void Request_weather_Information() {

    MODEL_INSTANCE.Establishing_DB_Communication();

    Log.e("test", String.valueOf(MODEL_INSTANCE.getsizearry()));
    // Log.e("Size", String.valueOf(MODEL_INSTANCE.Weather_Information().getCity()));
}

错误消息是:空对象引用上的'int java.util.List.size()' 为什么会发生

1 个答案:

答案 0 :(得分:1)

如果异常来自for循环,则countryModels可以为null。如果response.body().getCountryModels();没有返回countryModels的实例,则在.size()上调用countryModels会给您一个空指针。

如果异常来自Request_weather_Information()方法或getsizearry()方法,请尝试将ARRAYS传递到RequestWeatherInformation()方法和getsizearry()方法中,例如RequestWeatherInformation( List<CountryModel> ARRAYS)。由于这些方法是在单独的类中声明的,因此除非您将其传递,否则它们将无法从其他类访问ARRAYS大小。

相关问题