Calling Google Places API in a RecyclerView

北城余情 提交于 2019-12-11 06:53:49

问题


I have a RecyclerView whose adapter fetches details about a place ID using the Google Places API. The adapter then displays those details (eg. place address) in each element of the RecyclerView.

Is there a recommended way to achieve this asynchronously? In my current solution, the place addresses are sometimes displayed in the incorrect RecyclerView element when the user scrolls up or down. Also when tapping on a RecyclerView element to go to the detail screen, then going back to the original screen, some of the place addresses are missing in the RecyclerView (presumably there is a delay when the details are still being fetched from the Places API).

public void onBindViewHolder(final ViewHolder v, int position) {
    Places.GeoDataApi.getPlaceById(googleApiClient, placeID)
            .setResultCallback(new ResultCallback<PlaceBuffer>() {
                @Override
                public void onResult(PlaceBuffer places) {
                    Place place = places.get(0);

                    // Display address in the RecyclerView element
                    v.address.setText(place.getName());
                }
     }

回答1:


Dont hit api in onbindviewholder method. Because onbindviewholder method execute every time when you scroll recyclerview.

This will be better if you fetch data in activity or fragment and then , store that data in arraylist and pass to recyclerview adapter.

And problem of shuffling item position is due to recyclerview recycle every item on scroll.

So in your onbindviewholder method, set this property to viewHolder

viewHolder.setIsRecyclable(false);


来源:https://stackoverflow.com/questions/39553072/calling-google-places-api-in-a-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!