简体   繁体   English

Retrofit中如何通过回调访问onResponse方法中的数据?

[英]How to access data in onResponse method through callback in Retrofit?

I'm very new to retrofit and android app development in general.一般来说,我对 retrofit 和 android 应用程序开发还很陌生。 My problem is that I need to extract/return the List "listOfNames" somehow (eventually also "listOfMovies") from the onResponse Method but I could not figure out a way to do it or how to access the callback.我的问题是我需要从 onResponse 方法中以某种方式提取/返回列表“listOfNames”(最终也是“listOfMovies”),但我想不出一种方法来做到这一点或如何访问回调。

    listOfNames = new ArrayList<>();

    Retrofit retrofit= new Retrofit.Builder().baseUrl(Base_URL).addConverterFactory(GsonConverterFactory.create()).build();
    ApiInterface myInterface= retrofit.create((ApiInterface.class));

    Call<MovieResults> call = myInterface.listOfMovies(Category,YOUR_API_KEY,langua,PAGE);
    call.enqueue(new Callback<MovieResults>() {
        @Override
        public void onResponse(Call<MovieResults> call, Response<MovieResults> response) {
            MovieResults results= response.body();

            List<Result> listOfMovies = results.getResults();
            Result film = listOfMovies.get(1);

            for(int i = 0; i < listOfMovies.size();i++){
                listOfNames.add(listOfMovies.get(i).getTitle());
                Log.d("Movies", listOfMovies.get(i).getTitle());
            };

            String posterlink = poster_url_base_ + "/t/p/w200" + film.getPosterPath();
            Uri myUri = Uri.parse(posterlink);


            //Picasso.get().load(myUri).into(myImage);

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


            t.printStackTrace();

        }
    });

The JSON response from the API request looks as follows (example for the first two movies):来自 API 请求的 JSON 响应如下所示(前两部电影的示例):

 { "total_results": 10000, "page": 1, "total_pages": 500, "results": [ { "title": "Chick Fight", "genre_ids": [ 28, 35], "id": 682377, "original_language": "en", "original_title": "Chick Fight", "poster_path": "/4ZocdxnOO6q2UbdKye2wgofLFhB.jpg", "video": false, "vote_average": 5.9, "overview": "When Anna Wyncomb is introduced to an an underground, all-female fight club in order to turn the mess of her life around, she discovers she is much more personally connected to the history of the club than she could ever imagine.", "release_date": "2020-11-13", "vote_count": 38, "popularity": 2182.377, "adult": false, "backdrop_path": "/fTDzKoQIh1HeyjfpG5AHMi2jxAJ.jpg" }, { "title": "Hard Kill", "genre_ids": [ 28, 53], "id": 724989, "original_language": "en", "original_title": "Hard Kill", "poster_path": "/ugZW8ocsrfgI95pnQ7wrmKDxIe.jpg", "video": false, "vote_average": 5, "vote_count": 209, "release_date": "2020-10-23", "overview": "The work of billionaire tech CEO Donovan Chalmers is so valuable that he hires mercenaries to protect it, and a terrorist group kidnaps his daughter just to get it.", "popularity": 1565.855, "adult": false, "backdrop_path": "/86L8wqGMDbwURPni2t7FQ0nDjsH.jpg" },

just keep listOfMovies as a filed in your Activity and whenever you want you can extract titles or use it;只需将 listOfMovies 保留为 Activity 中的一个文件,您可以随时提取标题或使用它;

class ExampleActivity {

    private List<Result> listOfMovies =  new ArrayList();


   ...

   Call<MovieResults> call = myInterface.listOfMovies(Category,YOUR_API_KEY,langua,PAGE);
    call.enqueue(new Callback<MovieResults>() {
        @Override
        public void onResponse(Call<MovieResults> call, Response<MovieResults> response) {
            MovieResults results= response.body();
            listOfMovies.clear();
            listOfMovies.addAll(results.getResults());
....



    private List<String> getMoviesName(){
        List<String> listOfNames = new ArrayList();
        for(int i = 0; i < listOfMovies.size();i++){
                listOfNames.add(listOfMovies.get(i).getTitle());
                Log.d("Movies", listOfMovies.get(i).getTitle());
         };
       return listOfNames;
    }
}

if you want show names in a recyclerView you just need to create your recyclerView and at the end of onresponse add names to your adapter and then call notifyDataSetChanged() on your adapter如果你想在 recyclerView 中显示名称,你只需要创建你的 recyclerView 并在 onresponse 结束时将名称添加到你的适配器,然后在你的适配器上调用 notifyDataSetChanged()

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

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