ViewPager + RecyclerView issue in android

I see a lot of problems with your code, but let’s get your UI displaying the subcategories since that’s your main concern.

Change the getItem in your adapter to this:

        @Override
        public Fragment getItem(int position) {

            ArrayList<SubcategoryModel> subcategories = filelist.get(position).getItems();
            Log.v("adapter", "getitem" + String.valueOf(position)+subcategories.size());
            return FirstFragment.create(position,subcategories);
        }

What caused the problem:

Let’s focus on ArrayList<SubcategoryModel> subct in your activity:

First your code did this:

    for(int i = 0; i < filelist.size(); i++){
        ArrayList<SubcategoryModel> subct=filelist.get(i).getItems();
        // for(int j=0;j<subct.size();j++) ...
    }

So at the end of this loop subct is set the subcategories of the last category in filelist.

After that, you did another loop to load the tabs, but that used a different subct variable that was declared inside the loop, and that had no effect on the subct field of your activity.

Then you created your view pager and adapter.

In your pager adapter you had this:

    @Override
    public Fragment getItem(int position) {

        Log.v("adapter", "getitem" + String.valueOf(position)+subct.size());
        return FirstFragment.create(position,subct);
    }

Since subct was set to the last category’s subcategories from the loop before, every single fragment created was receiving those subcategories, no matter what position (category) the fragment was for. All I did was change the code to go back to filelist and get the correct category (and subcategories) for the position of the fragment being created.

When you’re writing code, you think about what you want the code to do. However, at the point where you run the code and discover you have a problem, you have to forget what you wanted the code to do, then pretend you’re the computer and run the code in your head. You want to understand what effect every line of code is having. When you do it that way it’s easier to find the problem.

Leave a Comment