1

How can I get the selected date from Calendar? This gives me the current date. Please check the code and tell me what's wrong with this.

final AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.Theme_AppCompat_DayNight_Dialog);
        final DatePicker picker = new DatePicker(getContext());

        builder.setView(picker);

        builder.setPositiveButton("Go to This Date", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    picker.setOnDateChangedListener(new DatePicker.OnDateChangedListener() {
                        @Override
                        public void onDateChanged(DatePicker datePicker, int yearSelected, int monthOfYear, int dayOfMonth) {
                            myCalendar.set(Calendar.YEAR, yearSelected);
                            myCalendar.set(Calendar.MONTH, monthOfYear);
                            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        }
                    });
                }
                Toast.makeText(getContext(), "" + sdf.format(myCalendar.getTime()), Toast.LENGTH_SHORT).show();
                dialogInterface.dismiss();
            }
        });

        builder.setCancelable(false);
        builder.show();
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Zand
  • 37
  • 10
  • 1
    check this https://stackoverflow.com/questions/39916178/how-to-show-datepickerdialog-on-button-click – nimi0112 Mar 12 '18 at 07:56

1 Answers1

0

Use DatePickerDialog.

Use like below.

DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
    new DatePickerDialog.OnDateSetListener() {   
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            txtDate.setText(checkDigit(monthOfYear + 1) + "-" + dayOfMonth  + "-" + year);
            currentDayCal.set(Calendar.DATE,dayOfMonth);
            currentDayCal.set(Calendar.MONTH,monthOfYear + 1);
            currentDayCal.set(Calendar.YEAR,year);
        }
    }, mYear, mMonth, mDay);
    datePickerDialog.show();
André Kool
  • 4,880
  • 12
  • 34
  • 44
  • I tried this code but the thing I want to set my background touch disable when calendar popups. That's why I used a AlertDialog here. is there anyway that I can disable background touch in DatePickerDialog ? – Zand Mar 12 '18 at 07:52
  • you can set datePickerDialog.setCancelable(false); As DatePickerDialog extends AlertDialog – Kousei Mar 12 '18 at 08:34
  • Thanks a lot.. this worked. Thank you for supporting me guys :) – Zand Mar 12 '18 at 09:39