androidandroid-recyclerviewpaginationadapterandroid-nestedscrollview

How to get single item which is visible to user in recyclerview but not all the loaded items from recyclerview?


Suppose we have pagination and after getting product from pagination api we have to call another api only for that particular product which is visible to user not all that product which get from pagination api

                    int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
                    int findFirstCompletelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
                    int findLastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                    int findLastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();

using above methods but not wroked for me according to my query.


Solution

  • // Step 1: RecyclerView Scroll
    rvImage.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }
    
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (currentPage == 1) {
                int firstItem = mLayoutManager.findFirstVisibleItemPosition();
                int lastItem = mLayoutManager.findLastVisibleItemPosition();
                for (itemPosition = firstItem; itemPosition <= lastItem; itemPosition++) {
                    // todo working code below
                    View childView = rvImage.getChildAt(itemPosition);
                    if (childView != null) {
                        int childTop = childView.getTop();
                        int childBottom = childView.getBottom();
    
                        if ((childBottom >= dy && childBottom <= dy + ns_view.getHeight())) {
                            // Item is visible
                            int childPosition = rvImage.getChildAdapterPosition(childView);
                            if (!modelList.get(childPosition).isImpressionSet()) {
                                Log.e("Post position==>", String.valueOf(childPosition));
                                Log.e("Post PostItem==>", String.valueOf(modelList.get(childPosition).getPrice()));
                                ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
                                executor.schedule(new MyRunnable(TagDetailActivity.this,
                                                modelList.get(childPosition), tagDetailAdapter,
                                                childPosition,
                                                HamaUtils.getaccesstoken(TagDetailActivity.this), true),
                                        2, TimeUnit.SECONDS);
                            }
                        } else {
                            Log.d("VisibleCount==>", "Item " + itemPosition + " is not visible");
                            break;
                        }
                    }
                }
            }
        }
    });
    
    // Step 2: NestedScrollView Scroll
    ns_view.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
        @Override
        public void onScrollChange(NestedScrollView nestedScrollView, int scrollX, int i1, int i2, int i3) {
            if (nestedScrollView.getChildAt(nestedScrollView.getChildCount() - 1) != null) {
                if ((i1 >= (nestedScrollView.getChildAt(nestedScrollView.getChildCount() - 1).getMeasuredHeight() - nestedScrollView.getMeasuredHeight())) &&
                        i1 > i3) {
                    // code to fetch more data for endless scrolling
                    visibleItemCount = mLayoutManager.getChildCount();
                    totalItemCount = mLayoutManager.getItemCount();
                    pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
                    if (loading) {
                        if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                            loading = false;
                            currentPage += 1;
                            progressBar.setVisibility(View.VISIBLE);
                            if (HamaUtils.isNetworkAvailable(TagDetailActivity.this)) {
                                getTagDetails(String.valueOf(currentPage));
                            }
                        }
                    }
                }
                if (itemPosition < modelList.size())
                    checkScrollVisibility(ns_view, i3, i1, itemPosition, false);
            }
        }
    });
    
    // Step 3: Function for checking visibility in nested scroll
    public void checkScrollVisibility(NestedScrollView nestedScrollView, int i1, int i3, int itemPosition, boolean isFirstTime) {
        View childView = rvImage.getChildAt(itemPosition);
        if (childView != null) {
            int childTop = childView.getTop();
            int childBottom = childView.getBottom();
    
            if ((childBottom >= i3 && childBottom <= i1 + nestedScrollView.getHeight())) {
                // Item is visible
                int childPosition = rvImage.getChildAdapterPosition(childView);
                if (!modelList.get(childPosition).isImpressionSet()) {
                    Log.e("Post position==>", String.valueOf(childPosition));
                    Log.e("Post PostItem==>", String.valueOf(modelList.get(childPosition).getPrice()));
                    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
                    executor.schedule(new MyRunnable(TagDetailActivity.this,
                                    modelList.get(childPosition), tagDetailAdapter,
                                    childPosition,
                                    HamaUtils.getaccesstoken(TagDetailActivity.this), false),
                            2, TimeUnit.SECONDS);
                }
            } else {
                // Item is not visible
                Log.d("VisibleCount==>", "Item " + itemPosition + " is not visible");
            }
        }
    }
    
    // Step 4: API call in background
    public class MyRunnable implements Runnable {
        Activity mContext;
        Post_Main postData;
        int position;
        String accesstoken;
        boolean isFirstTime = true;
    
        public MyRunnable(Activity context, Post_Main postData,
                          TagDetailAdapter adapter, int item,
                          String getaccesstoken, boolean isFirstTime) {
            this.mContext = context;
            this.position = item;
            this.accesstoken = getaccesstoken;
            this.postData = postData;
            this.isFirstTime = isFirstTime;
        }
    
        @Override
        public void run() {
            // This code runs in the background
            int result = setImpressionAndVisit(postData, position);
    
            // This code runs on the main thread
            mContext.runOnUiThread(() -> {
                // Update the UI with the result
            });
        }
    
        private int setImpressionAndVisit(Post_Main postData, int position) {
            try {
                APIService apiService = Config.getClient().create(APIService.class);
                Call<ResponseBody> call = apiService.setImpression(HamaUtils.getaccesstoken(TagDetailActivity.this),
                        HamaUtils.content_type, HamaUtils.getIpAddress(), postData.getID(),
                        HamaUtils.IMPRESSION_VISIT.impression.name(), HamaUtils.IMPRESSION_FROM.hashtag_page.name());
    
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.isSuccessful()) {
                            if (response.body() != null) {
                                String jstr = null;
                                try {
                                    jstr = response.body().string();
                                    JSONObject jsonobject = new JSONObject(jstr);
                                    if (response.code() == 200) {
                                        String code = jsonobject.optString("code");
                                        String error = jsonobject.optString("error");
                                        if (code.matches("200")) {
                                            JSONObject dataObject = jsonobject.optJSONObject("data");
                                            String message = dataObject.optString("message");
                                            Log.e("Impression Response==>", message);
                                            modelList.get(position).setImpressionSet(true);
                                            tagDetailAdapter.notifyItemChanged(position);
                                            if (!isFirstTime)
                                                itemPosition++;
                                        }
                                    }
                                } catch (Exception e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    }
    
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
    
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            return position;
        }
    }