亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法在 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 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號