The Date Picker dialog box does not work in the fragment

advertisements

here i have made a simple code for date picker which works for current date, year and day,it is not working for fragment

   public class Activity extends Sherlockfragment {

    EditText  dob;
    public static final int DATE_DIALOG_ID = 1009;
    String dob_string;
    int year = 2013, month = 10, day = 1, dayofmonth = 1;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
view = inflater.inflate(R.layout.update_profile, container, false);

            mdob = (EditText)view. findViewById(R.id.dob);
          mdob.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog(DATE_DIALOG_ID);
        }});
return view;
}

// ****************************#DATE PICKER DIALOG# **************************
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        // set date picker as current date
        return new DatePickerDialog(this, datePickerListener, year, month,
                day);
    }
    return null;
}

 private DatePickerDialog.OnDateSetListener datePickerListener = new   DatePickerDialog.OnDateSetListener() {
    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        year = selectedYear;
        month = selectedMonth + 1;
        day = selectedDay;
        Calendar cal = Calendar.getInstance();
        cal.set(selectedYear, selectedMonth, selectedDay);
        DateFormatSymbols dfs = new DateFormatSymbols(Locale.getDefault());
        String weekdays[] = dfs.getWeekdays();
        int daykk = cal.get(Calendar.DAY_OF_WEEK);
        String dayof = weekdays[daykk];
        mdob.setText(day + "-" + month + "-" + year + dayof);
        mdob_string = day + "-" + month + "-" + year;
    }};
    }


You can make a custom class for that as below :

public static class DatePickerFragment extends DialogFragment
                            implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
    }
}

Reference : Pickers with Fragment Hope this will help.