Search code examples
androidandroid-datepicker

How to fetch the date that has been changed in datepicker


Am developing an app, which first gets the current date from DatePicker using "Calendar.getInstance()", and then the user changes the date. Now how do I fetch the new date after it has been changed?


Solution

  • declear this .

    private static final int DATE_DIALOG_ID = 0;
    

    add this coding in onCreate()

     // add a click listener to the button
        date_text.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
    
        // get the current date      
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH); 
        String da = Integer.toString(mMonth)+"/"+Integer.toString(mDay)+"/"+Integer.toString(mYear);
        date_text.setText(da);
    

    and this is out side of onCreate()

     private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            String selectedDate = Integer.toString(mMonth)+"/"+Integer.toString(mDay)+"/"+Integer.toString(mYear);
            date_text.setText(selectedDate);
            System.out.println("selected date is:"+selectedDate);
        }
    };
    
    @Override
    protected Dialog onCreateDialog(int id)  {
        switch (id) {
    
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);        
        }
        return null;
    }