Ofek Agmon
Ofek Agmon

Reputation: 5198

android - check condition for selected date in onDateSet

I have an android app - and in one of the activities I raise a DatePickerDialog.OnDateSetListener for the user to select a date.

I want to make sure that the user chooses a date that it's week day is Wednesday, for example. my question is how can I check some condition about the selected date - and if necessary, put up a "please select another date" message and allow for the user to choose again.

Here is the code, All of this code is on OnCreate method

mCalendar = Calendar.getInstance();
        DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                // Here I want to check if the date is good. 
                // if its good - call GetPlayersList()
                // if not - raise a message and let user choose again
                mCalendar.set(Calendar.YEAR, year);
                mCalendar.set(Calendar.MONTH, monthOfYear);
                mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                new GetPlayersList().execute(Utilities
                        .getAccessToken(AttendanceActivity.this));
            }

        };

        new DatePickerDialog(AttendanceActivity.this, date,
                mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH),
                mCalendar.get(Calendar.DAY_OF_MONTH)).show();

Any ideas? thanks in advance

Upvotes: 0

Views: 1352

Answers (1)

Frederik Schweiger
Frederik Schweiger

Reputation: 8732

You could use mCalendar.get(Calendar.DAY_OF_WEEK):

int dayOfWeek = mCalendar.get(Calendar.DAY_OF_WEEK);

if(dayOfWeek == Calendar.WEDNESDAY) {
    // it is a Wednesday
} else {
    // it is not a Wednesday
}

Edit

It would look something like that:

private void showDialog() {
    final Calendar calendar = Calendar.getInstance();

    new DatePickerDialog(AttendanceActivity.this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, monthOfYear);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

            if(dayOfWeek == Calendar.WEDNESDAY) {
                // it is a Wednesday - do what you want
                new GetPlayersList().execute(Utilities.getAccessToken(AttendanceActivity.this));
            } else {
                // it is not a Wednesday - show the dialog again
                showDialog();
            }
        }
    },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)).show();
}

Upvotes: 2

Related Questions