简体   繁体   English

如何从 Retrofit onResponse 获取数据

[英]How do I get a data from a Retrofit onResponse

I want to get an ArrayList<ItemList> from my Retrofit Callback and save it in as a ArrayList variable in my class.我想从我的 Retrofit Callback 中获取一个ArrayList<ItemList>并将其保存为我的类中的ArrayList变量。 In other word I need to use data from retrofitList even when I leave the onResponse method.换句话说,我需要从使用数据retrofitList甚至当我离开onResponse方法。 What is the best way to do it?最好的方法是什么? Here is my code.这是我的代码。

@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) {}
    });
}

I recommend serialization it will make your life easier.我推荐序列化它会让你的生活更轻松。 Try this and this .试试这个这个 Create a method in your class that you will call from onResponse with your list.在您的类中创建一个方法,您将使用您的列表从 onResponse 调用该方法。 Save the list in some field variable.将列表保存在某个字段变量中。 If you call this variable before it is filled with items from onResponse it won't have them.如果在填充来自 onResponse 的项目之前调用此变量,它将没有它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM