Nuh Koca Nuh Koca - 5 months ago 19
JSON Question

Loop always sets the last data to TextView in Android

I get data from server side to my RecyclerView but the code always sets the last text to my TextView. I am so confused. Can you help me? Thanks. I am sharing my code below.

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());
}
});
}

Answer

As far as I can see, your subNodes was always the same instance?

So the subNodes number wasn't increased.

I think creating subNode should be in loop:

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();
}