【问题标题】:How do I get a data from a Retrofit onResponse如何从 Retrofit onResponse 获取数据
【发布时间】:2020-07-12 14:06:14
【问题描述】:

我想从我的 Retrofit 回调中获得一个 ArrayList<ItemList> 并将其保存为我班级中的 ArrayList 变量。 换句话说,即使我离开了onResponse 方法,我也需要使用来自retrofitList 的数据。 最好的方法是什么? 这是我的代码。

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    retrofitList = new ArrayList<>();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://b98afcf5.ngrok.io/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    jsonPlaceHolder = retrofit.create(JsonPlaceHolder.class);

    Call<List<ItemList>> call = jsonPlaceHolder.getItemList();
    call.enqueue(new Callback<List<ItemList>>() {
        @Override
        public void onResponse(Call<List<ItemList>> call, Response<List<ItemList>> response) {
            if(!response.isSuccessful()) {
                return;
            }
            List<ItemList> listOfitems = response.body();
            for(ItemList itemList : listOfitems){
                retrofitList.add(new ItemList(itemList.getId(),
                        itemList.getName(),
                        itemList.getPhone(),
                        itemList.getIsLocated()));
            }
            //I WANT TO SAVE "retrofitList" INTO MY CLASS FROM HERE
        }

        @Override
        public void onFailure(Call<List<ItemList>> call, Throwable t) {}
    });
}

【问题讨论】:

  • 您想将其保存在变量中吗?它已经保存了!
  • 嗨 Jamaldin,我想将列表保存到另一个变量中,以便在我的课堂上阅读它
  • 是的,您有 retrofitList 并且它存储了您在 for 循环中添加的值
  • 既然你已经在填充它,为什么不能通过retrofitList访问它?
  • 因为一旦我离开 onResponse 我丢失了我的数据,我想存储它

标签: java android asynchronous callback retrofit


【解决方案1】:

我推荐序列化它会让你的生活更轻松。试试thisthis。 在您的类中创建一个方法,您将使用您的列表从 onResponse 调用该方法。将列表保存在某个字段变量中。如果您在填充来自 onResponse 的项目之前调用此变量,它将没有它们。

【讨论】:

    猜你喜欢
    • 2017-07-26
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多