Search code examples
javaandroidparsingcollectionssimpledateformat

Parsing date crashes in Android 12


I am using the following code to parse date to sort a list:

Collections.sort(collaborationRoomModelList, new Comparator<CollaborationRoomModel>() {
                    DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");

                    @Override
                    public int compare(CollaborationRoomModel lhs, CollaborationRoomModel rhs) {
                        try {
                            return f.parse(rhs.getDate()).compareTo(f.parse(lhs.getDate()));
                        } catch (ParseException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                });

This code works perfectly fine on Android 7 but crashes in android 12. Below is the crash log:

java.lang.IllegalArgumentException: java.text.ParseException: Unparseable date: "Tue Jun 07 14:40:24 GMT+10:00 2022"
        at com.bizfluence.ui.business.collabmsglist.CollabMessageList$3$1.compare(CollabMessageList.java:389)
        at com.bizfluence.ui.business.collabmsglist.CollabMessageList$3$1.compare(CollabMessageList.java:381)
        at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
        at java.util.TimSort.sort(TimSort.java:220)
        at java.util.Arrays.sort(Arrays.java:1492)
        at java.util.ArrayList.sort(ArrayList.java:1470)
        at java.util.Collections.sort(Collections.java:206)
       

Any solution to fix this issue is greatly appreciated.


Solution

  • Adding the Local solved the issue. Works fine on both android 7 and 12.

    DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.US);