1

I want to download pics from Flickr in android app and show them in my RecyclerView (GridLayoutManager). Here is my code to fetch it with pages (by default page = 1)

public List<GalleryItem> fetchItems(Integer page){
    if (page==null) page=1;
    List<GalleryItem> items=new ArrayList<>();
    try {
        String url = Uri.parse("https://api.flickr.com/services/rest/")
                .buildUpon()
                .appendQueryParameter("method", "flickr.photos.getRecent")
                .appendQueryParameter("api_key", API_KEY)
                .appendQueryParameter("format", "json")
                .appendQueryParameter("nojsoncallback", "1")
                .appendQueryParameter("extras", "url_s")
                .appendQueryParameter("page",page.toString())
                .build().toString();
        String jsonString = getUrlString(url);
        Log.i(TAG, "Received JSON: " + jsonString);

        JSONObject jsonBody = new JSONObject(jsonString);
        parseItems(items,jsonBody);
}
    catch (JSONException jse){
        Log.e(TAG,"Failed to parse JSON",jse);
    }
    catch (IOException ioe){
        Log.e(TAG,"Failed to fetch items",ioe);
    }
    return items;
}

when i get these items i add them to recyclerviews adapters items and watch if I didn't reach its end to fetch new data in this case (used help from How to implement endless list with RecyclerView?)

private RecyclerView mPhotoRecyclerView;
private List<GalleryItem> mItems=new ArrayList<>();

GridLayoutManager mGridLayoutManager;
int pastVisibleItems, visibleItemCount, totalItemCount,currentpage=1;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.fragment_photo_gallery,container,false);

    mPhotoRecyclerView=(RecyclerView)v.findViewById(R.id.fragment_photo_gallery_recycler_view);
    mGridLayoutManager=new GridLayoutManager(getActivity(),3);
    mPhotoRecyclerView.setLayoutManager(mGridLayoutManager);
    mPhotoRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (dy>0) {
                visibleItemCount = mGridLayoutManager.getChildCount();
                totalItemCount = mGridLayoutManager.getItemCount();
                pastVisibleItems = mGridLayoutManager.findFirstVisibleItemPosition();
              //  ppastVisibleItems = mGridLayoutManager.findLastVisibleItemPosition();


                if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
                    currentpage++;
                    new FetchItemsTask().execute(new Integer[]{currentpage});
                }
            }
        }
    });
    setAdapter();
    return v;
}

private void setAdapter(){
    if(isAdded()){
        mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
    }
}

my AsyncTask Implementation

private class FetchItemsTask extends AsyncTask<Integer,Void,List<GalleryItem>>{

        @Override
        protected List<GalleryItem> doInBackground(Integer... voids) {
//            try{
//
//                String result=new FlickrFetchr().getUrlString("https://www.bignerdranch.com");
//                Log.i(TAG,"Fetched contents of URL: "+result);
//            }
//            catch (IOException ioe){
//                Log.e(TAG,"Failed to fetch URL: "+ioe.getMessage(),ioe);
//            }
            return new FlickrFetchr().fetchItems(currentpage);
        }

        @Override
        protected void onPostExecute(List<GalleryItem> items) {
            mItems.addAll(items);
            setAdapter();
        }
    }

the problem is i think in piece

 if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
                currentpage++;
                new FetchItemsTask().execute(new Integer[]{currentpage});
            }

every time i spend more and more time to scroll view down. First scroll: totalItemCount=100 , it works fine. At the next scroll pastVisibleItems gets equal 0, totalItemCount =200 (flickr gives pages by 100) and thereby it takes more and more time to redownload new pics. i tried to use

if ((visibleItemCount + pastVisibleItems+(currentpage-1)*100) >= totalItemCount) {
                    currentpage++;
                    new FetchItemsTask().execute(new Integer[]{currentpage});
                }

but then recycler view keeps showing me first page(. How can I implement it correctly?

Here are my Adapter and ViewHolder codes

private class PhotoHolder extends RecyclerView.ViewHolder{
    private TextView mTitleTextView;
    public PhotoHolder(View itemView) {
        super(itemView);
        mTitleTextView=(TextView)itemView;
    }
    public void bindGalleryItem(GalleryItem item){
        mTitleTextView.setText(item.toString());
    }
}

private class PhotoAdapter extends RecyclerView.Adapter<PhotoHolder>{
    private List<GalleryItem> mGalleryItems;

    public PhotoAdapter(List<GalleryItem> galleryItems) {
        mGalleryItems=galleryItems;
    }

    @Override
    public PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        TextView textView=new TextView(getActivity());
        return new PhotoHolder(textView);
    }

    @Override
    public void onBindViewHolder(PhotoHolder holder, int position) {
        holder.bindGalleryItem(mGalleryItems.get(position));
    }

    @Override
    public int getItemCount() {
        return mGalleryItems.size();
    }
}
Community
  • 1
  • 1
Ilqar Rasulov
  • 169
  • 1
  • 2
  • 10

1 Answers1

0

I've found answer, the problew why pastVisibleItems was set to zero was because of generating of new instance of adapter in

private void setAdapter(){
if(isAdded()){
    mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
}

}

i changed it to

private void setAdapter(){
    if(isAdded()){

        if (mPhotoRecyclerView.getAdapter()==null)
            mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
        else
            mPhotoRecyclerView.getAdapter().notifyDataSetChanged();
    }
}

and now everything works superbly! Thanks for attention)

Ilqar Rasulov
  • 169
  • 1
  • 2
  • 10