I'm trying to open a dialog for picking a date on Android. Here is my code :
et_date = (EditText) findViewById(R.id.et_date);
et_date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
And I have this class :
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
}
}
And I get this error :
Attempt to invoke virtual method 'void android.widget.EditText.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
How can I fix this? Thanks.
Problem is:
et_date is null. You are tried to set listener for null object. That's why, It gives this error. Double check with your layout xml.
For debugging, just add null check and set lisetner to "et_date" as below
if (ed_date != null)
{
// print log here to find this as error.
// set listener here..
}
Update from your comments:
Add below code in your fragment. Move the variable "ed_date" to your fragment, it should not be in Activity.
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ed_date = (EditText) view.findViewById(R.id.ed_date);
}