Encountering a slight issue with implementing a Date picker using a fragment into another fragment. Upon clicking the button to load the Date picker, an error message is logged:
java.lang.ClassCastException: com.example.buzzamaid.HomeActivity cannot be cast to android.app.DatePickerDialog$OnDateSetListener
at com.example.buzzamaid.Fragments.DatePickerFragment.onCreateDialog(DatePickerFragment.java:23)
The assumption is that it's trying to pass it into HomeActivity instead of the DateTimeFragment created. How can this be resolved?
Datepickerfragment Code:
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getContext(),(DatePickerDialog.OnDateSetListener) getContext(), year, month, day);
}
}
DateTimeFragment Code:
Unbinder unbinder;
@BindView(R.id.bt_select_date)
Button bt_select_date;
@BindView(R.id.bt_select_time)
Button bt_select_time;
@BindView(R.id.tv_selected_date)
TextView tv_selected_date;
@BindView(R.id.tv_selected_time)
TextView tv_selected_time;
static DateTimeFragement instance;
public static DateTimeFragement getInstance() {
if (instance == null)
instance = new DateTimeFragement();
return instance;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View itemView = inflater.inflate(R.layout.fragment_date_time,container,false);
unbinder = ButterKnife.bind(this,itemView);
return itemView;
}
@OnClick(R.id.bt_select_date)
public void onClick() {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getFragmentManager(), "Date Picker");
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
tv_selected_date.setText(currentDateString);
}
}
How can the calendar be displayed without crashing when clicking the button in the fragment?