Search code examples
androidandroid-viewpager

How would i handle a two dimensional array in a viewpager android?


I have exam paper data stored in the form illustrated below:

enter image description here

I am trying to get a view pager to display this information sequentially, but have no clue what to do. I would like the view pager to show all the questions in one section and then move on to the next section and show the questions in there and so on, if there is a next section. if there is no next section the paper comes to an end. This will allow me to make exam papers with different sections and different kinds of questions. my current view pager code just shows the questions in one section and is like this:

public class QuestionAdapter extends android.support.v13.app.FragmentStatePagerAdapter  {

    private  int NUM_ITEMS;

    public QuestionAdapter(FragmentManager fragmentManager, int num_items){
        super(fragmentManager);

        NUM_ITEMS = num_items;

    }

    @Override
    public int getCount(){
        return NUM_ITEMS;
    }



    @Override
    public Fragment getItem(int position){

        return  QuestionContainerFragment.newInstance(position);

    }

}

Solution

  • you can try something like this...

    public class QuestionAdapter extends FragmentStatePagerAdapter  {
    
        private  int NUM_ITEMS;
    
        // this is the object in which you are storing your data 
        private YourData yourData;
    
        //when you initialize the adapter, send your data
        public QuestionAdapter(FragmentManager fragmentManager, int num_items, YourData yourData){
            super(fragmentManager);
            NUM_ITEMS = num_items;
            this.yourData = yourData;  
        }
    
        @Override
        public int getCount(){
            return NUM_ITEMS;
        }
    
    
    
        @Override
        public Fragment getItem(int position){
            //based on position, send appropriate data to your fragment   
            switch(position){
               case 0:   
                 return  QuestionContainerFragment.newInstance(yourData.sectionOne);
    
               case 1:   
                 return  QuestionContainerFragment.newInstance(yourData.sectionTwo);
    
               case 2:   
                 return  QuestionContainerFragment.newInstance(yourData.sectionThree);
    ....
    ....
    ....
            }
        }
    
    }
    

    In your QuestionContainerFragment, parse and show the data that you just sent.