0
votes

I'm trying to make an ArrayList with Holidays and dates (both Strings), then convert date to Calendar, get the day of week (using DAY_OF_WEEK) and/or sort by date/name, but for some reason I get the same result (Calendar) for every item on the list.

This is my code:

    public static ArrayList  listOfHolidays = new ArrayList();

        Holidays.holidaysList.add(new Holidays("Sukkot", "09/10/2014"));
        Holidays.holidaysList.add(new Holidays("Hanukkah", "17/12/2014"));
        Holidays.holidaysList.add(new Holidays("Purim", "16/03/2014"));

Holidays class:


    Calendar calendar = Calendar.getInstance();

    @Override
    public String toString() {
    //DayOfWeek is just an enum of days (strings)
        return holidayName + " falls on "
                    + DayOfWeek.values()[Calendar.DAY_OF_WEEK - 1]; // Here i get the same day each time
    }

    @Override
        public int compareTo(Holidays another) {
            if(MainActivity.sortByName == true) {
                    return holidayName.compareToIgnoreCase(another.holidayName);
            }
            return convertStringToCal() - another.convertStringToCal();
        }

        private int convertStringToCal() {
            int year, month, day;
            day = Integer.valueOf(holidayDate.substring(0, 2));
            month = Integer.valueOf(holidayDate.substring(3, 5));
            year = Integer.valueOf(holidayDate.substring(6, 10));
            calendar = Calendar.getInstance();
            calendar.set(year, month, day);
            return (int) calendar.getTimeInMillis();
        }

I call

Collections.sort()
from within a radioButton method to sort.
3
FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes. Much of the java.time functionality is back-ported to Java 6 & Java 7 in the ThreeTen-Backport project. Further adapted for earlier Android in the ThreeTenABP project. See How to use ThreeTenABP….Basil Bourque

3 Answers

1
votes

I see multiple reasons why it may not work.

First i don't know if you omitted part of the code of you Holidays class but you never actually set the calendar object aside from the convertStringToCal() method but i don't see if this method is also called in the constructor.

Secondly and most likely your problem:

@Override
    public String toString() {
    //DayOfWeek is just an enum of days (strings)
        return holidayName + " falls on "
                                        // Here you are using the constant Calendar.DAY_OF_WEEK
                    + DayOfWeek.values()[Calendar.DAY_OF_WEEK - 1]; // Here i get the same day each time
    }

It should actually look something like this:

@Override
    public String toString() {
    //DayOfWeek is just an enum of days (strings)
        return holidayName + " falls on "
                    + DayOfWeek.values()[calendar.get(Calendar.DAY_OF_WEEK)]; // Now you won't get the same day every time. :)
    }

Some additional notes:

I would use Date objects to hold the dates, and use SimpleDateFormat to convert Strings to Dates and the other way around.

If you use these two your Holidays class would look something like this:

public class Holidays {

        private final Calendar calendar = Calendar.getInstance();
        private final String holidayName;

        public Holidays(String holidayName, Date date) {
            this.holidayName = holidayName;
            this.calendar.setTime(date);
        }

        @Override
        public int compareTo(Holidays another) {
            // Generally you should avoid passing information statically between Activities
            if(MainActivity.sortByName == true) {
                    return holidayName.compareToIgnoreCase(another.holidayName);
            }
            return getTimeInMillis() - another.getTimeInMillis();
        }

        public long getTimeInMillis() {
            return this.calendar.getTimeInMillis();
        }

        @Override
        public String toString() {
        //DayOfWeek is just an enum of days (strings)
            DayOfWeek day = DayOfWeek.values()[calendar.get(Calendar.DAY_OF_WEEK)]; // Now you won't get the same day every time. :)
            return String.format("%s falls of %s", this.holidayName, day);
        }

    }

You can create Date objects like this:

// Create date objects with calendar.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, 3);
calendar.set(Calendar.DAY_OF_MONTH, 27);
Date date = calendar.getTime();

The Constructors of the Date object like new Date(year, month, day) are deprecated and should not be used. Always use a Calendar instance to create date objects.

With SimpleDateFormat you can convert String and Date objects like this:

// The String pattern defines how date strings are parsed and formated
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

String dateString = "09/10/2014";

// Convert a String to Date
Date dateFromDateString = sdf.parse(dateString);

// Convert a Date to a String
String dateStringFromDate = sdf.format(dateFromDateString);

If you need more than just simple conversion of Date and String objects you can use DateFormat. That is pretty much the Rolls Royce of Date String conversion. It can parse and format Strings in a much more general way without actually requiring a pattern and it automatically accounts for locale and much more.

Or you could just use JodaTime :)

0
votes

I think the problem is in casting to int in this part of code: return (int) calendar.getTimeInMillis();

calendar.getTimeInMillis() returns long, and casting to int should cause a problem.

0
votes

tl;dr

holidays.add( 
    new Holiday( 
        LocalDate.of( 2018 , Month.MAY , 8 ) , 
        "National Coconut Cream Pie Day" 
    ) 
)

java.time

This work is so much simpler with the modern java.time classes rather than obsolete legacy Calendar class and its commonly-used subclass, GregorianCalendar.

Table of all date-time types in Java, both modern and legacy

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Custom class

You misused the name Holidays twice in your code, once as the name of the list collection and once as the name of the individual "holiday" class/object. Furthermore, the first used as holding a static class variable, not likely a good design.

I will assume the second is a typo, and the second should be Holiday as the name of the class representing a particular holiday on a particular date.

Your Holiday class would look something like this.

class Holiday
{
    private LocalDate localDate;
    private String name;
    private DayOfWeek dow;

    public Holiday ( LocalDate localDateArg , String nameArg )
    {
        this.localDate = localDateArg;
        this.name = nameArg;
    }

    public LocalDate getLocalDate ( )
    {
        return localDate;
    }

    public String getName ( )
    {
        return name;
    }

    // With arguments.
    public String format ( Locale locale , FormatStyle style )
    {
        String date = this.localDate.format( DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale ) );
        String output = date + " | " + this.name;
        return output;
    }

    @Override
    public String toString ( )
    {
        return "Holiday{ " +
                "localDate=" + localDate +
                ", name='" + name + '\'' +
                " }";
    }
}

Next, we use that class.

List

Instantiate an empty List. You can optionally set the initial capacity of the ArrayList.

List < Holiday > holidays = new ArrayList <>( 3 );

Populate that list.

holidays.add( new Holiday( LocalDate.of( 2018 , Month.MAY , 8 ) , "National Coconut Cream Pie Day" ) );
holidays.add( new Holiday( LocalDate.of( 2018 , Month.AUGUST , 9 ) , "National Rice Pudding Day" ) );
holidays.add( new Holiday( LocalDate.of( 2018 , Month.JANUARY , 5 ) , "National Whipped Cream Day" ) );

holidays.toString():

[Holiday{ localDate=2018-05-08, name='National Coconut Cream Pie Day' }, Holiday{ localDate=2018-08-09, name='National Rice Pudding Day' }, Holiday{ localDate=2018-01-05, name='National Whipped Cream Day' }]

Sort with Comparator

To sort, pass an implementation of Comparator. Here is the classic Java syntax.

holidays.sort( new Comparator < Holiday >()
{
    @Override
    public int compare ( Holiday o1 , Holiday o2 )
    {
        int c = o1.getLocalDate().compareTo( o2.getLocalDate() );
        return c;
    }
} );

Here is that same Comparator in modern Java syntax using a lambda.

holidays.sort( ( o1 , o2 ) ->
{
    int c = o1.getLocalDate().compareTo( o2.getLocalDate() );
    return c;
} );

Or even shorter lambda syntax, but not necessarily better.

holidays.sort( ( o1 , o2 ) -> o1.getLocalDate().compareTo( o2.getLocalDate() ) );

Either way, the results are:

holidays.toString():

[Holiday{ localDate=2018-01-05, name='National Whipped Cream Day' }, Holiday{ localDate=2018-05-08, name='National Coconut Cream Pie Day' }, Holiday{ localDate=2018-08-09, name='National Rice Pudding Day' }]

Formatting output

For your date with day-of-week, use the format method we defined that automatically localized to the human language and cultural norms we specify with a Locale and FormatStyle.

for ( Holiday holiday : holidays )
{
    System.out.println( holiday.format( Locale.CANADA_FRENCH , FormatStyle.FULL ) );
}

vendredi 5 janvier 2018 | National Whipped Cream Day

mardi 8 mai 2018 | National Coconut Cream Pie Day

jeudi 9 août 2018 | National Rice Pudding Day

Or in US English, passing Locale.US:

Friday, January 5, 2018 | National Whipped Cream Day

Tuesday, May 8, 2018 | National Coconut Cream Pie Day

Thursday, August 9, 2018 | National Rice Pudding Day

Note that you can get a DayOfWeek enum object from LocalDate. From that you can automatically localize the name of that day with the DayOfWeek::getDisplayName method.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.