How to show previously selected date in DatePickerDialog on next call?

DatePickerDialog is loaded into the Snippet, which today displays as the default date when the dialog opens. Then the user selects the date, and then the dialog is rejected. The next time you reopen, how do I show the previously selected date as the default date, and not show today's date?

I tried .set () in Activity, but don't know how to use .get () to retrieve the date in a fragment. I tried a listener interface between Activity and fragement, but couldn't make it work, and it seems too complicated for the simple task I'm trying to accomplish. And I tried the package sent from Activity to the fragment, but I could not get this to work. Please inform.

Action 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 date? 
}

}

+4
7

DatePicker :

@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();
}
});
+1

Bundle :

@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 date? 
}

, , .

+1

private DatePicker datepicker;

   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();
}
+1

, sharedPreferences

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
}

sharedPreferences, .

0

,

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

//

    public static String getCurrentDate(String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    String formattedDate = sdf.format(Calendar.getInstance().getTime());
    return formattedDate;
    }
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

" " , Dailog Datepicker as , " ".

, "".

, ,

. , .

  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();
}
0

Source: https://habr.com/ru/post/1608433/


All Articles