5

A DatePickerDialog is loaded in a Fragment with today's showing as the default date when the dialog is first opened. The user then selects a date and then the dialog is dismissed. On next re-open, how do I show the previously selected date as the default date rather than it showing today's date?

I have tried .set() in the Activity but don't know how to use .get() to retrieve the date in the fragment. I've tried an interface with a listener between the Activity and the fragement but could not get that to work and it seems overly complicated for the simple task I am trying to achieve. And I've tried a bundle sent from the Activity to the fragment but I haven't been able to get that to work either. Please advise.

Activity file:

...
final Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");

Fragment file:

...
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);

    return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
    // Save selected date in a date variable here?  How?
    // How do I then use the date variable in onCreateDialog
    // rather than the get(Calendar) code that returns today's date? 
}

}

AJW
  • 1,578
  • 3
  • 36
  • 77
  • save it to a variable and when open athe dialog again set the picker your date variable. – David Sep 22 '15 at 07:17
  • @ajw look at http://stackoverflow.com/questions/11527051/get-date-from-datepicker-using-dialogfragment – sean Sep 22 '15 at 07:19
  • You should save the value in SharedPreferences. This is the appropriate Android api for saving isolated values between multiple opening and closing of the app. – JDenais Sep 22 '15 at 07:23
  • @sean What part of that thread? I set up a listener and it didn't work and it appeared overly complex. – AJW Sep 22 '15 at 07:24
  • @David First I need to show today's date as the default...that I can easily do (see above fragment code). On next open I need to set the picker with the previously selected date. Can you provide an example that I can try? – AJW Sep 22 '15 at 07:50
  • i have made an answer to you – David Sep 22 '15 at 08:49

7 Answers7

1

Get a DatePicker with default today date:

@SuppressLint("SimpleDateFormat")
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
private Calendar calendar = null;

int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
OnDateSetListener dateSetListener = new OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(year, monthOfYear, dayOfMonth);
//this line save-s the DatePicker selected date to the edittext
//you can try with:  Date dpDate =new Date(sdf.format(calendar.getTime();
birthDate.setText(sdf.format(calendar.getTime()));
}
};

final DatePickerFragment datePickerFragment = new DatePickerFragment(StepSettingsView.this, dateSetListener, year, month, day);
datePickerFragment.getDatePicker().setMaxDate(new Date().getTime());
datePickerFragment.show();
                    datePickerFragment.getButton(DatePickerDialog.BUTTON_NEUTRAL).setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
birthDate.setText("");
datePickerFragment.dismiss();
}
});
David
  • 2,331
  • 4
  • 29
  • 42
1

In Bundle you should send the year month and day value and retreive here like:

@Override
public Dialog onCreateDialog(Bundle mBundle) {

    int year = mBundle.getInt("YEAR");
    int month =  mBundle.getInt("MONTH");
    int day =  mBundle.getInt("DAY");

    return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
    // Save selected date in a date variable here?  How?
    // How do I then use the date variable in onCreateDialog
    // rather than the get(Calendar) code that returns today's date? 
}

From where we are calling this date time picker fragment from there you need to send this bundle.

Deepak Gupta
  • 979
  • 1
  • 10
  • 18
1

Declare Globally

private DatePicker datepicker;

Copy and paste below function

   private void selectDate() {

    final DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {

                    datepicker = new DatePicker(getActivity());

                    datepicker.init(year, monthOfYear + 1, dayOfMonth, null);


                }
            }, mYear, mMonth, mDay);

    if (datepicker != null) {
        datePickerDialog.updateDate(datepicker.getYear(), datepicker.getMonth() - 1, datepicker.getDayOfMonth());

    }
    datePickerDialog.show();
}
Digvijay Machale
  • 601
  • 7
  • 12
0

if i follow you question than put the date in sharedPreferences on

public void onDateSet(DatePicker view, int year, int month, int day) {
// here put you date to shared preference in get later//
// you can convert it to time stamp and easily save
}

By using sharedPreferences you can set any where and get any where in your application.

SRB Bans
  • 3,096
  • 1
  • 10
  • 21
0

Please get this

private String lastStoredDate;


    if(lastStoredDate == null || lastStoredDate.trim().length() == 0){
        lastStoredDate = getCurrentDate("MM/dd/yyyy");
    }
    String dobSplit[] = lastStoredDate.split("/");
    Calendar calendar = Calendar.getInstance();
    calendar.set(Integer.parseInt(dobSplit[2]), Integer.parseInt(dobSplit[0]), Integer.parseInt(dobSplit[1]));
    int iDay=calendar.get(Calendar.DATE);
    int iMonth=calendar.get(Calendar.MONTH)-1;
    int iYear=calendar.get(Calendar.YEAR);
    DatePickerDialog dbDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            StringBuilder date = new StringBuilder();

            monthOfYear = monthOfYear + 1;
            if (monthOfYear < 10) {
                date.append("0"+monthOfYear+"/"+dayOfMonth);
            }else{
                date.append(monthOfYear).append("/"+dayOfMonth);
            }
            date.append("/"+year);
          lastStoredDate = date.toString();
        }
    },iYear,iMonth,iDay);
    dbDialog.getDatePicker().setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);

    dbDialog.show();

// To get currrent date

    public static String getCurrentDate(String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    String formattedDate = sdf.format(Calendar.getInstance().getTime());
    return formattedDate;
    }
Ashish Agrawal
  • 1,977
  • 2
  • 18
  • 32
  • Thank you. You don't show "onCreateDialog" method at all. Is that not needed because you use "dbDialog.show();" ? – AJW Sep 22 '15 at 21:47
  • is your work done or not ? split method is used to get year month and day to set in calendar – Ashish Agrawal Sep 23 '15 at 04:39
  • I loaded your suggested code in Android Studio and I have about 25 complaints...must be abstract, lastStoredDate is unknown class, doesn't like calendar.set or parseInt. Can't resolve OnDateSetListener, class or interface expected, and a few others...no way I can diagnose all of these issues on my own. – AJW Sep 23 '15 at 05:09
0
First of all this code is working on `edittext` or any button to set previous and current date in to Date picker.                

public class AboutMeActivity extends AppCompatActivity {

DatePickerDialog datePickerDialog;
private TextInputEditText   edtDateOfBirth;
private int mYear;
private int mMonth;
private int mDay;

private  View.OnClickListener edtDateOfBirthClickListener    =   new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        datePickerDialog = new DatePickerDialog(AboutMeActivity.this, new DatePickerDialog.OnDateSetListener() { 

       @Override
       public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {

          //here i=year,i1= month,i2=days.

            mYear =i;
            mMonth=i1;
            mDay=i2;

            edtDateOfBirth.setText(i2 + "-" + (i1 + 1) + "-" + i);
       }

    }, mYear, mMonth, mDay);

   datePickerDialog.show();
 }};                     

  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);            
       edtDateOfBirth = (TextInputEditText)findViewById(R.id.edtDateOfBirth);     if(edtDateOfBirth!=null)edtDateOfBirth.setOnClickListener(edtDateOfBirthClickListener);  

  Calendar c = Calendar.getInstance();
  mYear = c.get(Calendar.YEAR); // current year
  mMonth = c.get(Calendar.MONTH); // current month
  mDay = c.get(Calendar.DAY_OF_MONTH); //current Day.       

}

}
0

My Edit text field displays the current date and updates the last selected date when the Datepicker Dailog as opens next time by fetching the values from the edit text field and updating the Date picker dialog.

I have a very detailed explanation of the on click function that I have set on the Edit text field.

I have posted the entire function as you can see from the comments which parts can be used for your problem

Note: I am not catching null values as I am displaying current date by default in my edit text view.

  public void setDateDialog(View view) {
    // Edit text field which on click opens the Datepicker Dialog
    final EditText eText = findViewById(R.id.timeField);
    // Get the current value in the edit text field
    String userInput = eText.getText().toString();
    // Remove the date seprators
    String[] dateParts = userInput.split("/");
    // Day String
    String dayStr = dateParts[0];
    // Month String
    String monthStr = dateParts[1];
    // Year String
    String yearStr = dateParts[2];
    // Day String to integer
    final int dayInt = Integer.parseInt(dayStr);
    // Month String to integer ( Substarct 1 as month as count starts from 0)
    final int monthInt = Integer.parseInt(monthStr)-1;
    // Year String to integer
    final int yearInt  = Integer.parseInt(yearStr);
    // Initialise the calender
    final Calendar cldr = Calendar.getInstance();
    int day = cldr.get(Calendar.DATE);
    int month = cldr.get(Calendar.MONTH);
    int year = cldr.get(Calendar.YEAR);

    DatePickerDialog pickerDialog = new DatePickerDialog(QuickLaunch.this, R.style.DatePickerTheme, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
           // Adding Zero before month if month is single digit
            int month = monthOfYear + 1;
            String fm = "" + month;
            String fd = "" + dayOfMonth;
            if (month < 10) {
                fm = "0" + month;
            }
            if (dayOfMonth < 10) {
                fd = "0" + dayOfMonth;
            }
            eText.setText(fd + "/" + (fm) + "/" + year);
        }
    }, year, month, day);
    // Set the maximum date till tommorrow
    pickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 1));
    // Set the minimun date till yesterday
    pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 1));
    //Set the previous date in datepicker
    pickerDialog.getDatePicker().init(yearInt,monthInt,dayInt,null);
    pickerDialog.show();
}
Varun
  • 45
  • 6