繁体   English   中英

Android Retrofit-在onclick方法之前等待响应完成

[英]Android Retrofit - wait response finish before onclick method

我正在使用翻新和Google Maps API的地方,并希望将它们收集在列表中。 但是此过程异步进行,因此我的列表始终返回0。是否有任何方法等待改型响应?

我想使用allItems列表,但是不能,因为这个问题。 如果有人可以帮忙,我将不胜感激

这是我的代码

我的全球

ArrayList<MapData.ResultsBean> myList;
ArrayList<MapData.ResultsBean> allItems;

按钮点击

menuOption1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myList = new ArrayList<MapData.ResultsBean>();
                allItems = new ArrayList<MapData.ResultsBean>();

                    allItems.addAll(selectAll("restaurant", myList));
                    allItems.addAll(selectAll("cafe", myList));
                    allItems.addAll(selectAll("bar", myList));

                // Always return 0
                Log.v("Size", "Places List size : " + allItems.size() + "");
        });

selectAll功能

private ArrayList<MapData.ResultsBean> selectAll(final String type, final ArrayList<MapData.ResultsBean> list){

    // Creating an object of our api interface
    ApiService myApi = RetroClient.getApiService();

    // Calling JSON
    Call<MapData> call = myApi.getNearbyPlaces(type, mLastLocation.getLatitude() + "," + mLastLocation.getLongitude(), PROXIMITY_RADIUS);

    call.enqueue(new Callback<MapData>() {
        @Override
        public void onResponse(Call<MapData> call, Response<MapData> response) {

            Log.v("Response Code", "Response Code is : " + response.code());

            if (response.isSuccessful()){

                try {

                    for (int i = 0; i < response.body().getResults().size(); i++) {
                        addToList(list, response.body().getResults().get(i));
                    }

                    Log.v(type, "List Size : " + list.size() + "");

                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }

            } else {
                Toast.makeText(getApplicationContext(), "Something work wrong", Toast.LENGTH_LONG).show();
            }

        }

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

            Toast.makeText(getApplicationContext(), "On Failure", Toast.LENGTH_LONG).show();
        }
    });

    Log.v("Size", "Size of all list : " + list.size() + "");
    return list;

}

我的介面

public interface ApiService {

    @GET("/maps/api/place/nearbysearch/json?sensor=true&key=MY_KEY")
    Call<MapData> getNearbyPlaces(@Query("type") String type, @Query("location") String location, @Query("radius") int radius);

}

我的MapData模型

public class MapData {

    private String next_page_token;
    private String status;
    private List<?> html_attributions;

    private List<ResultsBean> results;

    public String getNext_page_token() {
        return next_page_token;
    }

    public void setNext_page_token(String next_page_token) {
        this.next_page_token = next_page_token;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public List<?> getHtml_attributions() {
        return html_attributions;
    }

    public void setHtml_attributions(List<?> html_attributions) {
        this.html_attributions = html_attributions;
    }

    public List<ResultsBean> getResults() {
        return results;
    }

    public void setResults(List<ResultsBean> results) {
        this.results = results;
    }

    public static class ResultsBean {
        /**
         * location : {"lat":28.6217885,"lng":77.217058}
         * viewport : {"northeast":{"lat":28.6221309,"lng":77.21731114999999},"southwest":{"lat":28.6207613,"lng":77.21647215000002}}
         */

        private GeometryBean geometry;
        private String icon;
        private String id;
        private String name;
        /**
         * open_now : true
         * weekday_text : []
         */

        private OpeningHoursBean opening_hours;
        private String place_id;
        private double rating;
        private String reference;
        private String scope;
        private String vicinity;
        /**
         * height : 2304
         * html_attributions : ["<a href=\"https://maps.google.com/maps/contrib/109950289718771609910/photos\">Rakesh Arora<\/a>"]
         * photo_reference : CoQBdwAAAN7Lk09qvlJpI3LD176UvFqgRK9noYU9zlx0zrOxlBaMzNAeay5pCPlggL-Nd0wVq2hZATJnEL8ZfFdDKRjxOjbH1w04c1EH8t_1iGbyiLj0qurpPb8F6xEyEAT61z37fJzQF5GkS6eZFEIYT0GzFM5bPuFgjSzQJuw6WYmFvk7jEhBzXaMryJPjUO1JtNtdBH2KGhTbSxdPgvE-fnauqam3l0AvFEIusw
         * width : 4096
         */

        private List<PhotosBean> photos;
        private List<String> types;

        public GeometryBean getGeometry() {
            return geometry;
        }

        public void setGeometry(GeometryBean geometry) {
            this.geometry = geometry;
        }

        public String getİcon() {
            return icon;
        }

        public void setİcon(String icon) {
            this.icon = icon;
        }

        public String getİd() {
            return id;
        }

        public void setİd(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public OpeningHoursBean getOpening_hours() {
            return opening_hours;
        }

        public void setOpening_hours(OpeningHoursBean opening_hours) {
            this.opening_hours = opening_hours;
        }

        public String getPlace_id() {
            return place_id;
        }

        public void setPlace_id(String place_id) {
            this.place_id = place_id;
        }

        public double getRating() {
            return rating;
        }

        public void setRating(double rating) {
            this.rating = rating;
        }

        public String getReference() {
            return reference;
        }

        public void setReference(String reference) {
            this.reference = reference;
        }

        public String getScope() {
            return scope;
        }

        public void setScope(String scope) {
            this.scope = scope;
        }

        public String getVicinity() {
            return vicinity;
        }

        public void setVicinity(String vicinity) {
            this.vicinity = vicinity;
        }

        public List<PhotosBean> getPhotos() {
            return photos;
        }

        public void setPhotos(List<PhotosBean> photos) {
            this.photos = photos;
        }

        public List<String> getTypes() {
            return types;
        }

        public void setTypes(List<String> types) {
            this.types = types;
        }

        public static class GeometryBean {
            /**
             * lat : 28.6217885
             * lng : 77.217058
             */

            private LocationBean location;
            /**
             * northeast : {"lat":28.6221309,"lng":77.21731114999999}
             * southwest : {"lat":28.6207613,"lng":77.21647215000002}
             */

            private ViewportBean viewport;

            public LocationBean getLocation() {
                return location;
            }

            public void setLocation(LocationBean location) {
                this.location = location;
            }

            public ViewportBean getViewport() {
                return viewport;
            }

            public void setViewport(ViewportBean viewport) {
                this.viewport = viewport;
            }

            public static class LocationBean {
                private double lat;
                private double lng;

                public double getLat() {
                    return lat;
                }

                public void setLat(double lat) {
                    this.lat = lat;
                }

                public double getLng() {
                    return lng;
                }

                public void setLng(double lng) {
                    this.lng = lng;
                }
            }

            public static class ViewportBean {
                /**
                 * lat : 28.6221309
                 * lng : 77.21731114999999
                 */

                private NortheastBean northeast;
                /**
                 * lat : 28.6207613
                 * lng : 77.21647215000002
                 */

                private SouthwestBean southwest;

                public NortheastBean getNortheast() {
                    return northeast;
                }

                public void setNortheast(NortheastBean northeast) {
                    this.northeast = northeast;
                }

                public SouthwestBean getSouthwest() {
                    return southwest;
                }

                public void setSouthwest(SouthwestBean southwest) {
                    this.southwest = southwest;
                }

                public static class NortheastBean {
                    private double lat;
                    private double lng;

                    public double getLat() {
                        return lat;
                    }

                    public void setLat(double lat) {
                        this.lat = lat;
                    }

                    public double getLng() {
                        return lng;
                    }

                    public void setLng(double lng) {
                        this.lng = lng;
                    }
                }

                public static class SouthwestBean {
                    private double lat;
                    private double lng;

                    public double getLat() {
                        return lat;
                    }

                    public void setLat(double lat) {
                        this.lat = lat;
                    }

                    public double getLng() {
                        return lng;
                    }

                    public void setLng(double lng) {
                        this.lng = lng;
                    }
                }
            }
        }

        public static class OpeningHoursBean {
            private boolean open_now;
            private List<?> weekday_text;

            public boolean isOpen_now() {
                return open_now;
            }

            public void setOpen_now(boolean open_now) {
                this.open_now = open_now;
            }

            public List<?> getWeekday_text() {
                return weekday_text;
            }

            public void setWeekday_text(List<?> weekday_text) {
                this.weekday_text = weekday_text;
            }
        }

        public static class PhotosBean {
            private int height;
            private String photo_reference;
            private int width;
            private List<String> html_attributions;

            public int getHeight() {
                return height;
            }

            public void setHeight(int height) {
                this.height = height;
            }

            public String getPhoto_reference() {
                return photo_reference;
            }

            public void setPhoto_reference(String photo_reference) {
                this.photo_reference = photo_reference;
            }

            public int getWidth() {
                return width;
            }

            public void setWidth(int width) {
                this.width = width;
            }

            public List<String> getHtml_attributions() {
                return html_attributions;
            }

            public void setHtml_attributions(List<String> html_attributions) {
                this.html_attributions = html_attributions;
            }
        }
    }
}

这是我的聊天室

V/Size: Places List size : 0
V/restaurant: List Size : 20
V/bar: List Size : 21
V/cafe: List Size : 41

在使用Retrofit的异步方法时,您将立即返回列表,您将需要等待onResponse回调上的结果。

一种方法是使用回调接口异步报告结果。

public interface GetDataCallback {
   void onGetMapData(MapData mapData);
   void onError();
}

private void selectAll(final String type, final GetDataCallback getDataCallback){

    // Creating an object of our api interface
    ApiService myApi = RetroClient.getApiService();

    // Calling JSON
    Call<MapData> call = myApi.getNearbyPlaces(type, mLastLocation.getLatitude() + "," + mLastLocation.getLongitude(), PROXIMITY_RADIUS);

    call.enqueue(new Callback<MapData>() {
        @Override
        public void onResponse(Call<MapData> call, Response<MapData> response) {
            if (response.isSuccessful()){
               getDataCallback.onGetMapData(response.body());
            } else {
                getDataCallback.onError();
            }
        }

        @Override
        public void onFailure(Call<MapData> call, Throwable t) {
           getDataCallback.onError();
        }
    });
}

你可以称它为

selectAll("restaurant", new GetDataCallback(){
   @Override
   public void onGetMapData(MapData mapData) {
      // Parse your data
   }

   @Override
   public void onError() {
   }
});

for (;;)之后for (;;)在您的onResponse方法中编写此代码。

allItems.addAll(selectAll("restaurant", myList));
                allItems.addAll(selectAll("cafe", myList));
                allItems.addAll(selectAll("bar", myList));

暂无
暂无

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

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