【问题标题】:Unable to get List from response.body() from GET Retrofit Android无法从 GET Retrofit Android 的 response.body() 获取列表
【发布时间】: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


【解决方案1】:

首先需要检查您的响应大小是否大于 0(零)。

if(productGet.size() > 0){
    //Code...
}

同时检查 productList 的大小是否大于 0(零)。

【讨论】:

  • proGet 在 onResponse 方法中返回大小为 25,但是当我在 onResponse 方法之外调用 proGet 但仍在 createDummyData() 内时,proGet 大小返回 0,并给我超出范围的索引错误。我想知道为什么。
  • 当我尝试在 SingleItemModel ArrayList 中添加项目时
  • 检查productGet和productList的大小都大于零
  • proList返回25,proGet在onReponse()里面时返回25;但是,当我在 onResponse() 之外调用 proGet 时,它返回的大小为 0
  • proGet 在 onResponse 中初始化,所以很明显在外面它的值是零,没有初始化它没有任何对象,所以
猜你喜欢
  • 1970-01-01
  • 2015-12-07
  • 2016-08-05
  • 2016-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多