java – IndexOutOfBoundsException while swiping ViewPager

My application crashed while I was scrolling between cards on the ViewPager and this was the error that I got:

java.lang.IndexOutOfBoundsException: index=5 count=4″

I have absolutely no clue how to fix the index error but I think it is coming from the ArrayList that I have set up.

Adapter class:

public class DashboardFlavorAdapter extends PagerAdapter {
    private Context context;
    private ArrayList<DashboardFlavorModel> modelArrayList;

    public DashboardFlavorAdapter(Context context, ArrayList<DashboardFlavorModel> modelArrayList) {
        this.context = context;
        this.modelArrayList = modelArrayList;
    }

    @Override
    public int getCount() {
        return modelArrayList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view.equals(object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {

        //inflate layout flavor_item.xml
        View view = LayoutInflater.from(context).inflate(R.layout.flavor_item, container, false);

        //initialize UID views from flavor_item.xml
        ImageView imageIv = view.findViewById(R.id.imageIv);
        TextView flavorTv = view.findViewById(R.id.flavorTv);
        TextView quantityTv = view.findViewById(R.id.quantityTv);

        ImageButton minusbutton = (ImageButton) view.findViewById(R.id.minusbutton);
        ImageButton plusbutton = (ImageButton) view.findViewById(R.id.plusbutton);

        //getting data
        DashboardFlavorModel model = modelArrayList.get(position);
        String title = model.getTitle();
        int image = model.getImage();
        int count = model.getCount();

        //setting data
        imageIv.setImageResource(image);
        flavorTv.setText(title);
        quantityTv.setText(String.valueOf(count));

        //listener
        minusbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (count>0){
                    model.setCount(count-1);
                } else if (count ==0){
                    Snackbar message = Snackbar.make(view, "You cannot have less than 0 QTY",Snackbar.LENGTH_LONG).setAction("UNDO", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {}
                    });
                    message.show();
                    model.setCount(count);
                }


            }
        });

        plusbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                model.setCount(count+1);
            }
        });


       //Logcat also linked this line of code as part of the issue
        container.addView(view, position);

        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View)object);
    }
}

Model class for getters+setters for components of each “card”:

public class DashboardFlavorModel {
    String title;
    int image,count;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

This is the fragment class where I initiated the ViewPager:

public class DashboardFragment extends Fragment {

    //calendar
    private FragmentDashboardBinding binding;
    private Button btn_date;
    private DatePickerDialog.OnDateSetListener dateSetListener;

    //flavor cards
    private ViewPager viewPager;
    private ArrayList<DashboardFlavorModel> modelArrayList;
    private DashboardFlavorAdapter dashboardFlavorAdapter;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        DashboardViewModel dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);

        binding = FragmentDashboardBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        //final TextView textView = binding.textDashboard;
        //dashboardViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);

        //button for *DELIVERYDATE*
        btn_date = root.findViewById(R.id.datebutton);
        btn_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH);
                int day = c.get(Calendar.DAY_OF_MONTH);

                //Theme_Holo_Dialog for spinner calendar
                DatePickerDialog dialog = new DatePickerDialog(getContext(), android.R.style.Theme_DeviceDefault_Dialog,dateSetListener, year , month , day);
                dialog.show();

            }
        });

        //date button listener
        dateSetListener = (datePicker, y, m, d) -> {
            m = m+1;
            String date = d+"/"+m+"/"+y;
            btn_date.setText("Deliver by: " +date);

        };


        //initialize UI views
        viewPager = (ViewPager) root.findViewById(R.id.flavorsVp);

        loadCards();

        return root;
    }

    private void loadCards(){
        //initialize list
        modelArrayList = new ArrayList<>();

        //adding items to list
        modelArrayList.add(new DashboardFlavorModel(
                "Red date",
                R.drawable.flavor1,
                0));

        modelArrayList.add(new DashboardFlavorModel(
                "Red date (NO sugar)",
                R.drawable.flavor2,
                0));

        modelArrayList.add(new DashboardFlavorModel(
                "Red date with LONGAN",
                R.drawable.flavor3,
                0));

        modelArrayList.add(new DashboardFlavorModel(
                "Red date with LONGAN (NO sugar)",
                R.drawable.flavor4,
                0));

        modelArrayList.add(new DashboardFlavorModel(
                "Osmanthus flower",
                R.drawable.flavor1,
                0));

        modelArrayList.add(new DashboardFlavorModel(
                "Osmanthus flower (NO sugar)",
                R.drawable.flavor2,
                0));

        modelArrayList.add(new DashboardFlavorModel(
                "Ginseng",
                R.drawable.flavor3,
                0));

        modelArrayList.add(new DashboardFlavorModel(
                "Pandan",
                R.drawable.flavor4,
                0));

        modelArrayList.add(new DashboardFlavorModel(
                "Cane sugar",
                R.drawable.flavor1,
                0));

        //setup adapter
        dashboardFlavorAdapter = new DashboardFlavorAdapter(getContext(),modelArrayList);
        //set adapter to viewpager
        viewPager.setAdapter(dashboardFlavorAdapter);
        //set default padding from left/right
        viewPager.setPadding(100,0,100,0);


    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

Leave a Comment