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 楼答案
如果异常来自for循环,
countryModels
可以为null。如果response.body().getCountryModels();
没有返回countryModels
的实例,那么在countryModels
上调用.size()
将给您一个空指针如果异常来自
Request_weather_Information()
方法或getsizearry()
方法,请尝试将ARRAYS
传递给RequestWeatherInformation()
方法和getsizearry()
方法,例如RequestWeatherInformation( List<CountryModel> ARRAYS)
。由于这些方法是在一个单独的类中声明的,除非您传递它,否则它们将无法从另一个类访问数组大小