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

Android闹钟提醒应用添加日期选择后触发java.lang.NullPointerException问题求助

Null Pointer Exception Fix for Android Alarm App

Hey there, let's squash that NullPointerException you're running into—this is a classic variable scope issue that's easy to fix.

The Root Cause

Your class-level member variable Calendar c is never actually assigned a value before you pass it to startAlarm(). In both onTimeSet() and onDateSet(), you're creating a local Calendar c variable (using Calendar c = Calendar.getInstance();) instead of modifying the member variable you declared at the top of MeeldetuletusActivity. Those local variables vanish as soon as the method finishes, leaving your member c stuck as null. When you click the third button, passing this null object into startAlarm() causes the crash when you try to call c.before().

The Fix

Update your date/time picker callback methods to use the member Calendar variable, and add a quick check to ensure the user has selected a date/time before triggering the alarm.

Modified Code Snippets for MeeldetuletusActivity.java:

  1. Fix the onTimeSet() method (no more local c variable):
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    // Initialize the member Calendar if it's null
    if (c == null) {
        c = Calendar.getInstance();
    }
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
}
  1. Fix the onDateSet() method (same logic):
@Override
public void onDateSet(DatePicker view, int aasta, int kuu, int paev) {
    // Initialize the member Calendar if it's null
    if (c == null) {
        c = Calendar.getInstance();
    }
    c.set(Calendar.YEAR, aasta);
    c.set(Calendar.MONTH, kuu);
    c.set(Calendar.DAY_OF_MONTH, paev);
}
  1. Add a safety check in the alarm button click listener:
nupp_alarm.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (c == null) {
            Toast.makeText(MeeldetuletusActivity.this, "Palun vali kuupäev ja kord enne meeldetuletust käivitamist!", Toast.LENGTH_SHORT).show();
            return;
        }
        startAlarm(c);
    }
});

Why This Works

  • Now both pickers modify the same class-level Calendar object, so your selected date and time are merged into one valid instance.
  • The null check prevents crashes if the user tries to trigger the alarm without selecting a date or time first.
  • Your original time-only setup likely worked because you weren't overriding the member variable with a local one—adding the date picker introduced that scope mistake which broke everything.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 12:02:43