如何在可扩展列表视图中创建一组月份?

时间:2015-06-27 09:03:26

标签: android expandablelistview

如何在可扩展列表视图中创建一组月份并为每个月添加天数?我尝试像这样的循环

private void prepareListData() {
    months = new ArrayList<String>();
    days= new HashMap<String, List<String>>();
    daysArray = new ArrayList<String>();

    Calendar currentDate = Calendar.getInstance();

    for (int i = 50; i >= 0; i--) {
        String a = MyChangeDateFomatter.getStringDateFormatMonth(currentDate
                .getTimeInMillis());

        currentDate.add(Calendar.DATE, -1);
        if(months==null||(months.get(i).equalsIgnoreCase(months.get(i-1))==false)) {
            months.add(a);
            for (int j = 50; i >= 0; i--) {
                if(months.get(i).equalsIgnoreCase(months.get(i-1))==true) {
                    String b =  MyChangeDateFomatter.getStringDateFormatMonth(currentDate
                        .getTimeInMillis());
                    daysArray.add(b);
                    days.put(months.get(i),daysArray);
                }
                else {
                    days.put(months.get(i-1),daysArray);
                }
            }
        }   
    }
}

错误

  

java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.testexpandablelistview / com.example.testexpandablelistview.CalendarActivity}:    java.lang.IndexOutOfBoundsException:索引50无效,大小为0

请告诉我该怎么做?

1 个答案:

答案 0 :(得分:0)

您获得IndexOutOfBoundsException的原因是因为您尝试在列表中没有成员的情况下在第一个if语句中获取月份列表的第50位的项目。

以下代码应该为您提供正确的月份列表和天数哈希值。 (我还没有测试过,所以可能会有一些错误。)

    String a = MyChangeDateFomatter.getStringDateFormatMonth(currentDate
            .getTimeInMillis());
    months.add(a);
    daysArray.add(a);

    // Removed one since it was added outside the loop
    for (int i = 49; i >= 0; i--) { 
        currentDate.add(Calendar.DATE, -1);
        a = MyChangeDateFomatter.getStringDateFormatMonth(currentDate
                .getTimeInMillis());

        // Checks if a is in the months List
        if (!months.get(months.size() - 1).equals(a)) {
            days.put(months.get(months.size() - 1), daysArray);
            daysArray = new ArrayList<>();
            months.add(a);
        }
        daysArray.add(a);
    }

    days.put(months.get(months.size() - 1), daysArray);