有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java why方法返回列表的零大小<Country>

我有这个代码从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。列表空对象引用上的size() 为什么会这样


共 (1) 个答案

  1. # 1 楼答案

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

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