【发布时间】:2017-07-16 03:09:15
【问题描述】:
我正在尝试通过改造从 GET 请求中获取列表。但是每当我尝试从 response.body() 中访问列表值中的值(从数据库中检索数据成功)时,错误总是索引超出范围,列表返回 null。
我正在尝试使用列表中的所有数据填充我的 RecycleView。但是它总是返回 null,因此我的 RecycleView 总是空的。
下面是我的服务类的代码:
@GET("products/getallproducts") Call<List<Product>> getAllProducts();
用于检索我的列表并填充 RecycleView 的类:
public class HomeActivity extends AppCompatActivity {
List<Product> proGet = new ArrayList<Product>();
//some more codes here
//some more codes here
//some more codes here
//lastly followed by the method createDummyData()
public void createDummyData() {
Call<List<Product>> call = restServices.getService().getAllProducts();
call.enqueue(new Callback<List<Product>>() {
@Override
public void onResponse(Call<List<Product>> call, Response<List<Product>> response) {
int statusCode = response.code();
productGet = response.body();
//^^^this is where the problem is
//class used for populating one section
SectionDataModel dm = new SectionDataModel();
dm.setHeaderTitle("trend");
//class SingleItemModel is for adding single item into the section
ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
//adding each item into the SingleItem array list
singleItem.add(new SingleItemModel(proGet.get(0).status, productList.get(0).category));
singleItem.add(new SingleItemModel(proGet.get(0).name, productList.get(0).productid));
//populate the singleItem array list into one section
dm.setAllItemsInSection(singleItem);
//populate the whole RecycleView
allSampleData.add(dm);
}
@Override
public void onFailure(Call<List<Product>> call, Throwable t) {
}
});
}
`
logcat 中的错误如下:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kennethlo.kickgoo/com.example.kennethlo.kickgoo.HomeActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
我很绝望,希望有人能够提供帮助。提前致谢。
【问题讨论】:
-
您将
response.body()分配给productGet,然后在以下代码中引用proGet? -
是的,我需要在 onReponse() 之外使用 proGet。我需要在我声明的另一种方法中使用 proGet
标签: java android list null indexoutofboundsexception