Search code examples
javaandroidandroid-fragmentsdatepickerandroid-dialogfragment

Trying to set text of EditText from DatePicker DialogFragment


I am simply trying to get the date from a datepicker dialog I created from one of the many android datepicker tutorials I found online. I seem to be going wrong somewhere in the actual retrieving of the text date once it is selected. I have a DatePickerFragment class, which is called from a CreateEvent fragment which is nested inside my MainActivity activity class. This is the DatePicker:

public class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    private EditText txtDate;
    @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) {
        txtDate = (EditText)view.findViewById(R.id.txtDate);
        txtDate.setText(day + " " + (month + 1) + " " + year);
    }
}

I get Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence) on a null object reference when I actually try and set the date, which I understand means it can't actually find the edittext element in my create event fragment xml file.

How should I go about setting the text of this edittext element from onDateSet or do I have to change my approach?

I tried it this way but to no avail.


Solution

  • You need to use an interface to get the data from the datepicker to the caller fragment:

    public interface DateListener {
        void passDate(String date);
    }
    

    Create a member variable called mListener:

    private DateListener mListener;
    

    Override the onAttach & onDetach fragment methods:

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (DateListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DateListener");
        }
    }
    
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    

    Next, implement this interface in the caller fragment and override the passDate method:

    @Override
    public void passDate(String date) {
        // Do something with 'date', yourEditText.setText(date) for the example
    }
    

    And you should be good to go.