【问题标题】:can't get ArrayList outside of for loop in call.enqueue无法在 call.enqueue 中的 for 循环之外获取 ArrayList
【发布时间】:2019-06-27 13:32:17
【问题描述】:

我想从 Retrofit 中的 call.enqueue 方法的 for 循环中取出 ArrayList 数据。

如何访问 call.enqueue 方法之外的列表?

一切正常。打印列表大小时,我得到了我想要的价值。唯一的问题是我无法从 call.enqueue 方法之外访问值。

private void getSchoolList() {
    final Call<List<DanceSchool>> call = RetrofitClient.getInstance().getApi().getDanceSchools();


    call.enqueue(new Callback<List<DanceSchool>>() {
        @Override
        public void onResponse(Call<List<DanceSchool>> call, Response<List<DanceSchool>> response) {
            if(!response.isSuccessful()) {
                Toast.makeText(ListActivity.this, "Response Code: " + response.code(), Toast.LENGTH_SHORT).show();
            }

            List<DanceSchool> danceSchools = response.body();



            for(DanceSchool danceSchool:danceSchools){

                schoolNameList.add(danceSchool.getSchool_name());
                dayList.add(danceSchool.getDays());
                timingList.add(danceSchool.getSun_timing());
                contactNoList.add(danceSchool.getContact_no());
                addressList.add(danceSchool.getAddress());

            }


        }

        @Override
        public void onFailure(Call<List<DanceSchool>> call, Throwable t) {
            Toast.makeText(ListActivity.this, "Failure: "+t.getMessage(), Toast.LENGTH_SHORT).show();

        }
    });

}

我想在 call.enqueue 方法之外访问 ArrayList。

【问题讨论】:

    标签: java android retrofit retrofit2


    【解决方案1】:

    最简单的方法可能是声明一个函数,

    void accessArrayList(ArrayList<DanceSchool> danceSchool){
        //do stuff with the values
    }
    

    并在call.enqueue 内部调用它

    call.enqueue(new Callback<List<DanceSchool>>() {
        @Override
        public void onResponse(....) {
            ........
            List<DanceSchool> danceSchools = response.body();
            accessArrayList(danceSchools);
            .......
        }
    }
    

    【讨论】:

    • 你提前一分钟来了,所以让奖励快一点,先有代码。尽管最后,我们确实有相同的信息......
    【解决方案2】:

    重点是:现在您正在进行异步调用。您正在请求一些信息,并且当该信息已编译并准备好时然后调用onResponse() 方法。只有 然后 可以从传入的响应正文中填充该列表。

    因此,您可以做的是:在您的封闭类中使用另一个方法,例如 updateList(),然后在您的 onResponse() 实现中简单地调用该方法。

    除此之外,您可能希望将异步调用转换为同步调用。然后,改为使用execute() 等待结果出现(例如,参见here)。但是你仍然需要有一个回调方法来调用。

    或者,您可以在封闭类中有一个字段,例如

    List<DanceSchool> danceSchools
    ...
    private void getSchoolList() {
      final Call<List<DanceSchool>> call = ...    
      call.enqueue(new Callback<List<DanceSchool>>() {
        @Override
        public void onResponse(Call<List<DanceSchool>> call, Response<List<DanceSchool>> response) {
        ...
        danceSchools.addAll(response.body());
    

    【讨论】:

    • 感谢您的回答,但我的问题已解决。
    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多