I am trying to create a DatePicker dialog that opens when a button in my dialog made from a custom layout is pressed. I have tried many different configurations of code and the result when the button is pressed is always either a NullPointerException or the button does nothing. I am pretty new to android programming but my best guess is that findViewById is not able to find the button because I am working in a Fragment and the content view is not specified. I tried to use setContentView but that wasn't working. Hopefully someone can figure this out and let me know how they did it!
NewTaskDialogFragment.java:
public class NewTaskDialogFragment extends DialogFragment implements
android.view.View.OnClickListener {
public int mYear, mMonth, mDay;
public static final int DIALOG_ID = 0;
private Button btn;
private View dialogView;
public Dialog onCreateDialog(Bundle savedInstanceState) {
Context context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
dialogView= inflater.inflate(R.layout.new_task_dialog, null);
builder.setView(dialogView)
;
btn =(Button) dialogView.findViewById(R.id.datePickerDialogButton);
showDialogOnButtonClick();
return builder.create();
}
public void showDialogOnButtonClick(){
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().showDialog(DIALOG_ID);
}
});
}
private DatePickerDialog.OnDateSetListener dpickerListener
= new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
TextView dateDisplay = (TextView) getActivity().findViewById(R.id.dateDisplayBox);
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
dateDisplay.setText(mYear + mMonth + mDay);
}
};
@Override
protected Dialog onCreateDialog(int id){
if(id == DIALOG_ID) {
return new DatePickerDialog(getActivity(), dpickerListener , mYear, mMonth, mDay);
}else{
return null;
}
}
@Override
public void onClick(View view) {
}
}