为了账号安全,请及时绑定邮箱和手机立即绑定

无法在 call.enqueue 中的 for 循环之外获取 ArrayList

无法在 call.enqueue 中的 for 循环之外获取 ArrayList

哈士奇WWW 2023-02-23 17:30:43
我想通过 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。
查看完整描述

2 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

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


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

        .......

    }

}


查看完整回答
反对 回复 2023-02-23
?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

重点是:现在您正在进行异步调用。您正在请求一些信息,当该信息已编译并准备就绪时,onResponse()将调用该方法。只有这样,该列表才能从传入的响应正文中填充。


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


除此之外,您可能希望将异步调用变成同步调用。然后,相反,您使用execute()等待结果进来(例如,请参见此处)。但是你仍然需要有一个回调方法来调用。


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


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


查看完整回答
反对 回复 2023-02-23
  • 2 回答
  • 0 关注
  • 134 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号