欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

在一个Activity中,okhttp3中onResponse方法响应数据异步返回,不能立刻赋值给全局变量的问题

程序员文章站 2022-03-09 21:51:20
...

Android 学习采坑记录:----不知道把请求放在这里有什么影响,先这样吧
Activity.java:

		......
 private List<TradeGoods> tradegoodsList = new ArrayList<>();
   @Override
 protected void onCreate(Bundle savedInstanceState) {
        initTradeGoods();
//        sbsb!!!,解决异步数据不能立即赋给去全局变量问题,让它在活动创建前请求;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trade);
        ...
        ...
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        GridLayoutManager layoutManager = new GridLayoutManager(this,2);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new GoodsAdapter(tradegoodsList);
        recyclerView.setAdapter(adapter);
        ...
       }

initTradeGoods()方法,我在里面向服务端请求数据,然后向全局变量(List<TradeGoods>类型)tradegoodslist添加。

private void initTradeGoods(){

//现在没数据,直接请求完了,并放入了原来的数组,n,2n,3n数据都一样
        RequestBody requestBody = new FormBody.Builder().build();
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")
                .post(requestBody)
                .url("http://domain:port/transaction/getall")
                .build();
        HttpUtil.sendOkHttpRequest(request, new okhttp3.Callback() {

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String responsedata = response.body().string();
                Gson gson = new Gson();
                try {
                    JSONObject jsonObject = new JSONObject(responsedata);
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
//                    String test =gson.toJson(jsonArray);
//                    LogUtil.d(TAG,"test----"+test);
//                    LogUtil.d(TAG, "jsonArray:---" + jsonArray);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        tradegoodsList.add(gson.fromJson(jsonObject1.toString(), TradeGoods.class));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }
        });
    }