Search code examples
javaandroidhashmapindexoutofboundsexception

Hashmap is empty


when I'm running this part of code I get the IndexOutOfBoundException, because lessons hashmap is empty. I checked it in Debugger. Could you please explain why it is empty? I'm populating it with data, but it doesn't work properly.

public class ScheduleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.schedule_activity);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new SchedulePagerAdapter(getFragmentManager()));

    }

}


class SchedulePagerAdapter extends FragmentPagerAdapter {

    public SchedulePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return DayFragment.newInstance();
    }

    @Override
    public CharSequence getPageTitle(int position) {

        ArrayList<String> arrayList = new ArrayList<>();
        for (String key : LessonsMap.lessons.keySet()) {
            arrayList.add(key);
        }
        return arrayList.get(position);

    }

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

}


class LessonsMap {

    public static Map<String, String> lessons = new HashMap<String, String>();

    public LessonsMap() {

        lessons.put("Monday", "Test_Data");
        lessons.put("Tuesday", "Test_Data");
        lessons.put("Wednesday", "Test_Data");
        lessons.put("Thursday", "Test_Data");
        lessons.put("Friday", "Test_Data");
        lessons.put("Saturday", "Test_Data");


    }

}

Thanks!


Solution

  • You are never calling the constructor of LessonsMap which is where you are inserting the data in the map.

    You could make lessons not static and create a LessonsMap object like this:

    LessonsMap lessonsMap = new LessonsMap();
    

    and then lessons would be filled and accessible using lessonsMap.lessons.

    Otherwise, if you want to maintain lessons static you should initialize it using one of the methods discussed here: How can I initialise a static Map?