Loop始终将最后一个数据设置为Android中的TextView

时间:2016-06-26 01:37:20

标签: android json server retrofit android-cardview

我从服务器端获取数据到我的RecyclerView,但代码总是将最后一个文本设置为我的TextView。我感到很困惑。你能帮助我吗?谢谢。我在下面分享我的代码。

  private void bindDatas() {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(NewsService.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    NewsService newsService = retrofit.create(NewsService.class);
    final Call<NewsCatalog> requestCatalog = newsService.newsCatalog();


    requestCatalog.enqueue(new Callback<NewsCatalog>() {
        @Override
        public void onResponse(Call<NewsCatalog> call, Response<NewsCatalog> response) {
            NewsCatalog catalog = response.body();
            SubNodes subNodes = new SubNodes();
            mainNodes = new MainNodes();


            for (int i = 0; i < catalog.nodes.size(); i++) {
                mainNodes = catalog.nodes.get(i);
                Log.i(TAG, "" + mainNodes.node.body);

                subNodes.setBody(mainNodes.node.body);

                subNodesList.add(subNodes);
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onFailure(Call<NewsCatalog> call, Throwable t) {
            Log.e(TAG, "Error: " + t.getMessage());
        }
    });
}

1 个答案:

答案 0 :(得分:1)

据我所知,您的subNodes始终是同一个实例?

因此子节点数没有增加。

我认为创建subNode应该是循环的:

for (int i = 0; i < catalog.nodes.size(); i++) 
    mainNodes = catalog.nodes.get(i);
    Log.i(TAG, "" + mainNodes.node.body);

    subNodes = new SubNodes(); // ADD THIS LINE 

    subNodes.setBody(mainNodes.node.body);

    subNodesList.add(subNodes);
    adapter.notifyDataSetChanged();
}