【问题标题】:SimpleDateFormat freeze application on Android NAndroid N 上的 SimpleDateFormat 冻结应用程序
【发布时间】:2018-01-15 21:13:03
【问题描述】:

我使用一种方法将Date 的列表转换为String 以将它们显示给用户。此方法在 API

这是我的方法:

protected List<String> getValidPeriods() {
    ArrayList<String> validPeriods = new ArrayList<>();
    Date startDate = isSnis() ? Config.snisStartDate() : Config.dashboardsStartDate();
    Date endDate = new Date();

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);

    while(calendar.getTime().before(endDate)){
        validPeriods.add(DateUtils.format(calendar.getTime(), PERIOD_FORMAT));
        calendar.add(Calendar.MONTH, 1);
    }

    return validPeriods;
}

PERIOD_FORMAT在哪里

public static final String PERIOD_FORMAT = "MMMM yyyy";

DateUtils.format() 方法在哪里:

public static String format(Date date, String format) {
    if (date != null)
        return new SimpleDateFormat(format, Locale.getDefault()).format(date);
    return "";
}

我可以说这是引发问题的日期格式,因为删除行 return new SimpleDateFormat(format, Locale.getDefault()).format(date); 并用硬编码值替换它会停止应用程序的冻结。另一个指标是我们可以看到在方法跟踪期间它花费了 48.9% 的时间:

知道为什么吗?


更新 #1 另外,它的格式不正确。它应该给出“2016 年 11 月”,它给出“0008 年 11 月”。也许这是相关的。

【问题讨论】:

    标签: android performance simpledateformat android-7.0-nougat


    【解决方案1】:

    我在一个下面导入时遇到了同样的问题

    android.icu.text.SimpleDateFormat
    

    【讨论】:

    • 什么意思?我已经有了import java.text.SimpleDateFormat;。没有它,我的应用程序根本无法运行。
    • 有两个导入 import android.icu.text.SimpleDateFormat 和 java.text.SimpleDateFormat
    • 哦,好的,抱歉。但我正在使用java.text.SimpleDateFormat,它仍然冻结。 ://
    • 你尝试过使用这个 android.icu.text.SimpleDateFormat 吗?
    • 好吧,这都是我自己的误解。我教过你告诉我使用java.text.SimpleDateFormat。我试过icu.text.SimpleDateFormat,它解决了问题,谢谢!
    猜你喜欢
    • 2023-01-30
    • 1970-01-01
    • 2016-07-02
    • 2021-09-24
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多