Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnDateSetListener() not getting called

When I change date, OnDateSetListener() is not being called. Even setMinDate(day); line is not working. I think for some reason DatePickerDialog has not registered OnDateSetListener(). But not able figure it out. I have declared both dialog and listener as global.

private DatePickerDialog datePicker;
private DatePickerDialog.OnDateSetListener dateListener;

Code :

// Create dialogs for datePicker
private void createDatePicker() {

    Calendar calendar = Calendar.getInstance(Locale.getDefault());
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int month = calendar.get(Calendar.MONTH);
    int year = calendar.get(Calendar.YEAR);

    datePicker = new DatePickerDialog(this, dateListener, year, month, day);
    datePicker.getDatePicker().setMinDate(day);

    dateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            Log.d(TAG, "Date changed.");
        }
    };

}

private void setEditTextListeres() {
        myEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Log.d(TAG, "EditText gained focus.");
                    datePicker.show();
                }
            }
        });
    }

Any idea why listener is not being called? And why setMinDate() is not working?

like image 225
Geek Avatar asked Oct 30 '25 16:10

Geek


1 Answers

Create the DatePickerDialog after you declared the listener, like Rapunzel said.

The listener will not work, because dateListener is null when you create DatePickerDialog instance. The DatPickerDialog object will not detect changes made to your listener.

EDIT:

Because dateListener is null at the time of calling DatePickerDialog(). If you look at the source of the DatePickerDialog, you'll see the private final OnDateSetListener mCallback. That means it references to null. That reference becomes immutable, since it is final. dateListener = new DatePickerDailog.OnDateSetListener will create the instance somewhere else in the memory (because of the new keyword), causing the reference to change. The reference in DatePickerDialog.mCallback will not change, since it is immutable.

like image 113
Leon Joosse Avatar answered Nov 01 '25 05:11

Leon Joosse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!