dtc
dtc

Reputation: 10296

Android Datepicker Fragment - How to do something when the user sets a date?

I'm following the tutorial here: http://developer.android.com/guide/topics/ui/controls/pickers.html

I got things to work and the datepicker shows up. However, I am stuck on how to act on when the user sets the date.

I see they have this method:

public void onDateSet(DatePicker view, int year, int month, int day) {
    // Do something with the date chosen by the user
}

But that does nothing if I put any code in it.

I'm not that familiar with Java so I'm not sure what additional code is needed in order to update a textview with the chosen date.

I did add this code:

private DatePickerDialog.OnDateSetListener mDateListener =
        new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year, int month, int day) {
                updateDate(year, month, day);
            }
        };

public void updateDate(int year, int month, int day) {
    TextView bdate = (TextView)findViewById(R.id.birthDate);
    Date chosenDate = new Date(year, month, day);
    java.text.DateFormat dateFormat = DateFormat.getDateFormat(getApplicationContext());
    bdate.setText(dateFormat.format(chosenDate));
}

But that does nothing.

I did find this almost exact question: Get date from datepicker using dialogfragment

However in that solution wouldn't using (EditSessionActivity) limit the DatePickerFragment class to working with only the EditSessionActivity?

Upvotes: 16

Views: 19730

Answers (3)

Rodrigo Carrasco
Rodrigo Carrasco

Reputation: 91

in my experience this code work perfectly!, I'm using win10 Android Studio 2.2...

import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.app.DatePickerDialog;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;


public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);}

    public void datePicker(View view){
        DatePickerFragment fragment_date = new DatePickerFragment();
        fragment_date.show(getSupportFragmentManager(),"datePicker");}

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
         String day_x = ""+ day  ,month_x = ""+(month+1);
         if (day   < 9 ){ day_x   = "0" + day_x;}
         if (month < 9 ){ month_x = "0" + month_x;}
         ((EditText) findViewById(R.id.txtDate)).setText(day_x + "/" + month_x + "/" + year);}

    public static class DatePickerFragment extends DialogFragment {
        @Override
        public Dialog onCreateDialog (Bundle savedInstanceState){
            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);
            return new DatePickerDialog(getActivity() ,(DatePickerDialog.OnDateSetListener)this,day,month,year);}}

}

I've a "textView txtDate" and a "button with onclick = datePicker"

Upvotes: 1

KnowIT
KnowIT

Reputation: 2502

I believe one can use the DialogFragments here:

DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");

define the DatePickerFragment and implement the method below

public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
DateEdit.setText(day + "/" + (month + 1) + "/" + year);
}

taken from Android DialogFragment Example.

Upvotes: 2

GLee
GLee

Reputation: 5093

You should use a static factory to pass arguments to the DialogFragment. From the docs,

"Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments()."

Similarly, the Fragment subclass should be static, so that it can re-instantiate itself without relying on the parent activity or Fragment. If you don't adhere to these guidelines, you will sometimes get crashes or errors when your Fragment tries resume.

The recommended way to build a DialogFragment, from Android's docs, is to use a static factory method. Here's an example of a date picker fragment that takes in an initial date and an OnDateChangedListener:

public static class DatePickerFragment extends DialogFragment{

    private OnDateSetListener onDateSetListener;

    static DatePickerFragment newInstance(Date date, OnDateSetListener onDateSetListener) {
        DatePickerFragment pickerFragment = new DatePickerFragment();
        pickerFragment.setOnDateSetListener(onDateSetListener);

        //Pass the date in a bundle.
        Bundle bundle = new Bundle();
        bundle.putSerializable(MOVE_IN_DATE_KEY, date);
        pickerFragment.setArguments(bundle);
        return pickerFragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        super.onCreateDialog(savedInstanceState);

        Date initialDate = (Date) getArguments().getSerializable(MOVE_IN_DATE_KEY);
        int[] yearMonthDay = ymdTripleFor(initialDate);
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), onDateSetListener, yearMonthDay[0], yearMonthDay[1],
                yearMonthDay[2]);
        return dialog;
    }

    private void setOnDateSetListener(OnDateSetListener listener) {
        this.onDateSetListener = listener;
    }

    private int[] ymdTripleFor(Date date) {
        Calendar cal = Calendar.getInstance(Locale.US);
        cal.setTime(date);
        return new int[]{cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)};
    }
}

You can then create one of these dialog fragments as follows:

DatePickerFragment.newInstance(yourDate, yourOnDateSetListener);

Upvotes: 9

Related Questions