App crashes when the user changes the device language

我只是一个虾纸丫 提交于 2019-12-13 00:40:42

问题


I have an App that store some objects that contain a String date on a file, this String for some operations need to be parsed as GregorianCalendar. Now I have found this issue: when the user change the device language after the creation of the file the App become unable to process the stored file correctly and crashes returning this error

java.text.ParseException: Unparseable date: "27 Sep 2014 23:09:07" (at offset 3)
10-11 14:20:09.573    3745-3745/uk.myapp W/System.err﹕ at java.text.DateFormat.parse(DateFormat.java:561)

the method that returns this error is this

   public static GregorianCalendar stringInCalendar(String s, String formatPattern) {
        DateFormat format = new SimpleDateFormat(formatPattern);
        Date date = null;
        try {
            date = format.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        return cal;
    }

And the error happens on this line date = format.parse(s);

How could I fix this problem?

Note that this error happens only when the device language is changed regardless the type of date. If the device language remains the same, the method doesn't cause any crash


回答1:


In this line

DateFormat format = new SimpleDateFormat(formatPattern);

you use the default locale, and the default locale is associated to current language of device, if you change the Language the default locale doesn't match the locale used to store the String causing the error.

To avoid this issue you have to store the Locale used to get the String date and pass it to the DateFormat

DateFormat format = new SimpleDateFormat(formatPattern, localeOfTheDateString);

or store the date directly as GregorianCalendar objects



来源:https://stackoverflow.com/questions/26315275/app-crashes-when-the-user-changes-the-device-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!