Search code examples
javaandroiddatetimepicker

Put all the values user selects in a TimePicker in a list and read it


The title may be a litle confusing. I have a TimePicker for the user to pick a duration of an event, I wan't to get every value the user puts in, save it, and then set the default value of the TimePicker to the time that the user selects the most times, so it may save him time.

For example, if the user constantly selects 1h and 45m, when he goes back to add another event it will be in 1h and 45m, so far I havn't tried anything because I don't know how, I only know how to define the starting value of the TimePicker.

timePickerDuration.setIs24HourView(true);    
timePickerDuration.setCurrentHour(1);
timePickerDuration.setCurrentMinute(30);

Solution

  • As per your try till here, If your HoursList ArrayList contains the proper value, then you can loop like this and find the mostly selected hour,

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (Integer i : HoursList) {
        Integer count = map.get(i);
        map.put(i, count != null ? count+1 : 0);
    }
    
    Integer mostlySelectedhr = Collections.max(map.entrySet(),
        new Comparator<Map.Entry<Integer, Integer>>() {
        @Override
        public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    }).getKey();
    

    And finally mostlySelectedhr is the mostly selected hour.