Android闹钟提醒应用添加日期选择后触发java.lang.NullPointerException问题求助
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:
- Fix the
onTimeSet()method (no more localcvariable):
@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); }
- 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); }
- 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
Calendarobject, 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

