You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中java.lang.IllegalArgumentException报错排查求助

问题排查与解决

我帮你梳理了下这个崩溃问题,核心原因其实很明确:

从错误栈里的java.lang.IllegalArgumentException: Bad class: class java.lang.String可以看出,你调用DateFormat.format()方法时传入了字符串类型的参数,但这个方法只接受Date或者long类型的输入,这直接触发了崩溃。

看你代码里的这段关键逻辑:

deadline = sdf.parse(sdf.format(dateIns));

这里的dateIns是从数据库取出的日期字符串,你完全没必要用sdf.format()去处理它——format()是用来把Date转成字符串的,反过来解析字符串应该直接用parse()。另外你对todayDate的处理也属于多余操作,绕了没必要的弯路。

修改后的代码示例

Users_Database db = new Users_Database(context);
String currentUsrname = PreferenceManager.getDefaultSharedPreferences(context).getString("USRNFORBROADCAST", "NothingFound");
List<String> dates=db.getAllDates(db.findID(currentUsrname));

// 先处理日期字符串的换行问题
String dateIns = dates.get(0).replaceAll("\\n", "");
String dateVin = dates.get(1);
String dateTax = dates.get(2);

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
Date todayDate = c.getTime();
Date deadline = null;

try {
    // 直接解析数据库取出的日期字符串,无需多余的format操作
    deadline = sdf.parse(dateIns);
    if (deadline != null) {
        // 减去一周的毫秒数(7*24*60*60*1000 = 604800000L)
        deadline = new Date(deadline.getTime() - 604800000L);
    }
} catch (ParseException e) {
    e.printStackTrace();
    // 可以加日志提示,方便排查格式不匹配问题
    Log.e("DateParseError", "日期解析失败,原字符串:" + dateIns, e);
}

// 先判断deadline不为null,避免空指针异常
if (deadline != null && todayDate.before(deadline)) {
    Intent it = new Intent(context, BootServices.class);
    createNotification(context, it, "I Love My Car", "Краен срок!", "Изтичащ преглед");
    context.startService(it);
}

额外注意事项

  • 务必确保数据库中存储的日期字符串格式和SimpleDateFormat指定的dd/MM/yyyy完全匹配(比如05/10/2024这种格式),否则会触发ParseException。
  • 新增了deadline != null的判断,防止日期解析失败后出现空指针崩溃。
  • 去掉了todayDate多余的format再parse操作,直接使用Calendar获取的Date对象即可。

内容的提问来源于stack exchange,提问作者strelecaaaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:05:42