I have defined DatePickerFragment in my android application, here is the code for it:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { private int year; private int month; private int day; @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); } @Override public void onDateSet(DatePicker view, int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public Date getDateFromDatePicker(){ Calendar calendar = Calendar.getInstance(); calendar.set(year, month, day); return calendar.getTime(); } }
I want to retrieve the date from this date picker from TaskFragment, and set the "date" attribute in my class Task to be equal to the date selected
// Method for date picker to appear once the "Due Date" button is clicked.
datePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
DatePickerFragment datePicker = new DatePickerFragment();
datePicker.show(fm, "datePicker");
task.setDate(datePicker.getDateFromDatePicker());
//test
System.out.println(task.getDate());
}
});
The date picker appears when clicking the button. However, the date is not being set correctly, and is actually being set as soon as the date button is pressed, not when a date is selected from the picker. Also, when printing the date, I get the following no matter what date I select: I/System.out: Wed Dec 31 10:47:38 GMT+00:00 2 Reading some solutions here directed me to define the onDateSet and getDateFromDatePicker methods, but they do not seem to be functioning correctly. Any help is much appreciated, thank you!