misha312
misha312

Reputation: 1713

find last day in month and using value change listener in an android app

I am trying to build an app that uses dates. The user picks the date from a number picker. I wrote some code that should update the maximum number of days in the picker so that the user won't be able to choose a day that cant be found in some month (for example pick 31 in feb). I don't know why but my code doesn't work .

When I Pick February the maximum day is still 31. When I change the month again lets say I pick again January, the max day is now 28. The code works but with delay

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_week);
    final NumberPicker month= (NumberPicker)findViewById(R.id.month);
    final NumberPicker day = (NumberPicker)findViewById(R.id.day);
    final Button but= (Button)findViewById(R.id.button1);
    final TextView text=(TextView)findViewById(R.id.text);
    final TextView text2=(TextView)findViewById(R.id.text2);
    final TextView text3=(TextView)findViewById(R.id.text3);
    day.setMaxValue(31);
    day.setMinValue(1);
    month.setMinValue(1);
    month.setMaxValue(12);
    month.setOnValueChangedListener(new OnValueChangeListener() {

        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            // TODO Auto-generated method stub

            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MONTH,month.getValue());
            cal.set(Calendar.DAY_OF_MONTH,1);
            int d = 0;
            while(cal.get(Calendar.MONTH)==month.getValue()){

                cal.add(Calendar.DATE, +1);
                d=d+1;


            }


            if (day.getValue()>d){
                day.setValue(d);
            }
            day.setMaxValue(d);
        }
    } );

Upvotes: 1

Views: 600

Answers (3)

Prashant Thakkar
Prashant Thakkar

Reputation: 1403

Try following code snippet to get maximum number of days in a month :

int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

Upvotes: 0

user2058839
user2058839

Reputation:

Your problem is that you call month.getValue() that will be changed after onValueChenge()

Replace

while(cal.get(Calendar.MONTH)==month.getValue()){

By

while(cal.get(Calendar.MONTH)==newVal-1){

And also

cal.set(Calendar.MONTH,newVal-1);

Upvotes: 1

saiful103a
saiful103a

Reputation: 1129

What you are doing actually works. But i think you forgot one key factor days and month are 0 based indexing checkout : Calender

Try adjusting these to :

day.setMaxValue(30);
day.setMinValue(0);
month.setMinValue(0);
month.setMaxValue(11);

Upvotes: 1

Related Questions