Geek
Geek

Reputation: 8320

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?

Upvotes: 4

Views: 3957

Answers (1)

Leon Joosse
Leon Joosse

Reputation: 1079

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.

Upvotes: 5

Related Questions