Search code examples
androidandroid-intentdatepickeralarmmanagertimepicker

Getting Context inside a TimePickerDialog


I am creating an application where I present the user with a DatePicker and a TimePicker in order to create the future date values for an AlarmManager.

I am chaining the TimePicker to show when the user selects the Date in the DatePicker.

Then inside of the TimePicker, once the user selects the time, I want to create a pending intent and and set the AlarmManager. When I try to create an Intent however, I get a crash because it seems I cannot get context.

What is weird though is that if I create the Intent inside the DatePicker, it works.

public void onDateSet(DatePicker view, int year, int month, int day) {

    mCallback.onDateSelected(year, month, day);

    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, day);

    TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(), this, 1, 1, true);
    timePickerDialog.show();
}

/**
 * @param view
 * @param hourOfDay
 * @param minute
 */
@Override
public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {

    mTimeCallback.onTimeSelected(hourOfDay, minute);

    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
    calendar.set(Calendar.MINUTE, minute);
    Long millis = calendar.getTimeInMillis();
    long futureInMillis = SystemClock.elapsedRealtime() + millis;


    Intent notificationIntent = new Intent(getContext(), NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, getNotification());
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 100, pendingIntent);

    Log.i("Got here", "yes");
}

Solution

  • You can simply use view.getContext() inside onTimeSet()

    It won't be null.