如何将响应改造数据存储到列表中

时间:2019-06-11 14:20:04

标签: android list retrofit2 okhttp3

我正在移动android中进行改造,我想将响应数据存储到我的公共列表中,我已经尝试过,但是我的列表仍然为空,但是数据可以显示在onResponse中

这是我的改造

 private APIInterface getInterfaceService() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        final APIInterface mInterfaceService = retrofit.create(APIInterface.class);
        return mInterfaceService;
    }

    private void trendingQuestion(final List<Trending> listTrending){
        progressDialog.show();
        APIInterface mApiService = this.getInterfaceService();
        Call<ResponseTrendsQuestion> mService = mApiService.getTendingQuestion();
        mService.enqueue(new Callback<ResponseTrendsQuestion>() {
            @Override
            public void onResponse(Call<ResponseTrendsQuestion> call, Response<ResponseTrendsQuestion> response) {
                if(response.isSuccessful()){
                    for(int i=0;i<response.body().getData().size();i++) {
                        listTrending.add(new Trending(Integer.valueOf(response.body().getData().get(i).getId()),response.body().getData().get(i).getTitle(),
                                response.body().getData().get(i).getDescription(),
                                Integer.valueOf(response.body().getData().get(i).getLikes()),
                                Integer.valueOf(response.body().getData().get(i).getDislikes()),
                                Integer.valueOf(response.body().getData().get(i).getComment())));
                        Log.d("message",response.body().getData().get(i).getId());
                    }
                    progressDialog.dismiss();
                }else{
                    progressDialog.dismiss();
                    Log.d("message",response.errorBody().toString());
                    Toast.makeText(getContext(), response.errorBody().toString(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseTrendsQuestion> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(getContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
            }
        });
    }

我的列表

listTrending = new ArrayList<>();
        trendingQuestion(listTrending);

1 个答案:

答案 0 :(得分:0)

1)问题是您多次调用response.body(),而它仅返回一次body。

此处的第一个调用返回正文:

for(int i=0;i<response.body().getData().size();i++) {

所有其他呼叫返回空的主体。没有数据可添加到列表中,因为您在第一次通话时就丢失了数据。在循环之前将主体保存为变量,然后使用它。

2)假设改为使用CopyOnWriteArrayList是有意义的,因为ArrayList不是线程安全的(假设根据您的用例,您可以尝试同时修改它)。