Search code examples
androidandroid-fragmentsdatepickerandroid-dialogandroid-datepicker

Android- Datepicker at custom dialog


I got a custom dialog with a datepicker on it. On my Fragment i got a button and when i press it the dialog shows up and i select the date from the datepicker. I want the selected date to be shown on a textview in my Fragment. My code is below:

This is the code for the dialog on my main Activity that holds the Fragment:

public int day;
    public int month;
    public int year;

    @SuppressLint("InflateParams")
    @SuppressWarnings("deprecation")
    public void SetDate(){
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Select Date");
        alertDialog.setIcon(R.drawable.action_reservations);
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View promptView = layoutInflater.inflate(R.layout.datepicker, null);
        alertDialog.setView(promptView);
        final DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
        final TextView PickedDate = (TextView) findViewById(R.id.pickeddate);
        alertDialog.setButton("OK", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which) 
            {
                day=datePicker.getDayOfMonth();
                month=datePicker.getMonth() + 1;
                year=datePicker.getYear();
                PickedDate.setText(new StringBuilder().append(day).append(" ").
                        append("-").append(month).append("-").append(year));
            }

        });
        // Showing Alert Message
        alertDialog.show();
       }

I get the day, month and year from datepicker and set them to my textview with

PickedDate.setText(new StringBuilder().append(day).append(" ").
                            append("-").append(month).append("-").append(year));

Also in my fragment i call my dialog with the code below:

final Button SetDate = (Button)rootView.findViewById(R.id.selectdate);
        SetDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {       
                ((MainActivity) getActivity()).SetDate();            
            }  
            });

When i run my app i got a nullPointerException on these lines:

day=datePicker.getDayOfMonth();
month=datePicker.getMonth() + 1;
year=datePicker.getYear();

What im doing wrong? Thanks in advance


Solution

  • Try to replace

    final DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
    final TextView PickedDate = (TextView) findViewById(R.id.pickeddate);
    

    With this

    final DatePicker datePicker = (DatePicker) promptView.findViewById(R.id.datePicker1);
    final TextView PickedDate = (TextView) promptView.findViewById(R.id.pickeddate);