Dialog datePicker bounds - Android - android

I'm using a datePicker dialog to pick the date, and I must set a lower and an upper bound. How can i do this?
Should I use the public void onDateChanged(DatePicker view, int year, int month, int day) method?
Please be explicit because I'm working with Android from 4 days only!

I suppose a DatePicker can NOT have a bound range. But you can check the date picked by user yourself. And if the date is invalid, you can alert the user.

You can set the maxDate and minDate like this:
Date upperLimit = new Date();
Date lowerLimit = new Date();
DatePicker picker = new DatePicker(getContext());
picker.setMaxDate(upperLimit.getTime());
picker.setMinDate(lowerLimit.getTime());
Cheers

Related

Android DatePickerDialog Max Date visual bug

I'm experiencing a weird visual bug on new DatePickerDialog of Android widgets. I need to set a dialog's selectable date range as 1 month but it shouldn't also select a date from the future. Logic works as expected but the visuals have some sort of bug. Here is how it looks:
Note that the "5" is disabled, I cannot select it. However, it looks as selectable. What should I do to solve this issue? Any help is appreciated, thanks. (Today's day of month is also 5, I assume this bug comes from there.)
Edit: This is how I create the dialog.
#SuppressLint("ValidFragment")
public static class DateDialog extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
private static final long MONTH = 2592000000L;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// Use previous selected date in the date picker
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(DateUtils.getAtTimeTimestamp(startDate));
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), R.style.AppTheme_DialogTheme, this, year, month, day);
Date date = new Date(); // get current time
// get target maximum date which can be 1 month above
long targetDateTime = DateUtils.getAtTimeTimestamp(startDate) + MONTH;
if (date.getTime() < targetDateTime)
dialog.getDatePicker().setMaxDate(date.getTime()); // now because it can't be future
else
dialog.getDatePicker().setMaxDate(targetDateTime); // should also be one month above from the start date.
dialog.getDatePicker().setMinDate(DateUtils.getAtTimeTimestamp(startDate));
return dialog;
}
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2)
{
// logic between date selections
}
}
DateUtils.getAtTimeTimestamp(String date) basically converts a string to long integer that is time in milliseconds.

DatePicker selects date before minDate

Updates:
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// do some stuff
}
}, year, month, day);
DatePicker datePicker = datePickerDialog.getDatePicker();
datePicker.updateDate(2018, 2, 7);
datePicker.setMinDate(1272920400000L); //milliseconds since epoch for 2010.04.10
datePickerDialog.show();
The problem happens inside any DatePicker object, it's not because of my code. You just go inside a DatePickerDialog and try to replicate.
I have a DatePicker and I've set minDate to be 4th of May 2010.
But when you select, for example, 1st May 2011, and then click left arrow until you reach May 2010, it will be automatically selecte 1st May 2010, which is unavailable. Then, OK button will work.
What do you think about this? Is there a way to solve it? I've searched all the Internet and didn't find anything. Thank you!

How to set the limit on date in Date picker dialog

I want to put the limit on date so that user can not pick date more then that, for example if today is 1 January then User should not be able to select more then 7 dates , I mean he can not select 9 January. I also want him not to select the month and year. So I am putting a limit to set his task in one week.
what I have done so far is showing the date picker fragment and setting current date in it. the code in my main activity goes like this:
etSelectDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d("Date Change", "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
DateFormat df = DateFormat.getDateInstance();
etSelectDate.setText(df.format(c.getTime()));
//nextField.requestFocus(); //moves the focus to something else after dialog is closed
}
};
datePickerFragment.show(MainActivity.this.getSupportFragmentManager(), "datePicker");
}
});
and date picker fragment class goes like this :
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);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
//blah
}
}
till then its is working fine , but I do not know how to put the limit on date and rest of the months and year should be non Select able . I have seen many link such as like this , but I do not understand How can I do that and also there is nothing helpful on android site.
So please help me , How can I put limit of seven days only
Update
Through your replies I know how to set the max date in calender , so As I want to set the max date 7 days ahead of current date , I am still not getting it. the method I read so far is :
pickerDialog.getDatePicker().setMaxDate(new Date().getTime());
It is setting the current date as maximum, but How can I add 7 days ahead in it since it is Date object ? please help
You have the setMinDate(long) and setMaxDate(long) methods at your disposal. Both of these will work on API level 11 and above. Since you are using a DatePickerDialog, you need to first get the underlying DatePicker by calling the getDatePicker() method.
dpdialog.getDatePicker().setMinDate(minDate);
dpdialog.getDatePicker().setmaxDate(maxDate);
Source :Set Limit on the DatePickerDialog in Android?
You can calculate the minDate by using,
Date today = new Date();
Calendar c = Calendar.getInstance();
c.setTime(today);
c.add( Calendar.MONTH, -6 ) // Subtract 6 months
long minDate = c.getTime().getTime() // Twice!
Updated :
Replace the below line
return new DatePickerDialog(getActivity(), this, year, month, day);
with
// Create a new instance of DatePickerDialog and return it
DatePickerDialog pickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
pickerDialog.getDatePicker().setMaxDate(maxDate);
pickerDialog.getDatePicker().setMinDate(minDate);
return pickerDialog;
In some cases, when you set maximum date with a date without hours and minutes, you won't be able to select the maximum date you set.
For instance
Calendar maxDate = Calendar.getInstance();
maxDate.set(Calendar.DAY_OF_MONTH, day + 5);
maxDate.set(Calendar.MONTH, month);
maxDate.set(Calendar.YEAR, year);
datePickerDialog.getDatePicker().setMaxDate(maxDate.getTimeInMillis());
With the code block above, you can not click to your maxDate.
But if you add hours and minutes to like;
maxDate.set(Calendar.HOUR, 23);
maxDate.set(Calendar.MINUTE, 59);
to your maxDate, your last date will be clickable
by using
setMinDate and setMaxDate
MinDate
MaxDate
try this
DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();
Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMaxDate(calendar.getTimeInMillis());//set the current day as the max date or put yore date in miliseconds.
datePicker.setMinDate(calendar.getTimeInMillis());//set the current day as the min date or put your date in mili seconds format
return dpDialog;

Lollipop CalenderView DatePicker doesn't call OnDateChanged() method

I'm working with a DatePicker and finding that under Android 5.0 it will not call the OnDateChanged() method in its OnDateChangedListener when it's in CalendarView mode even though a new date has been selected. If android:datePickerMode="spinner" is set in the DatePicker's xml tag, the DatePicker will appear as spinners and it will call OnDateChanged() when a new date is selected. In earlier versions of Android, a DatePicker calls OnDateChanged() when a new date is selected in both CalendarView and Spinners versions. Here's the relevant code:
#SuppressLint("InflateParams")
View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker) v.findViewById(R.id.dialog_date_DatePicker);
datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
//Translate year, month, day into a Date object using a calendar
mDate = new GregorianCalendar(year, month, day).getTime();
//Update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
In my application, onDateChanged() doesn't get called and mDate doesn't get changed if the DatePicker is in CalendarView mode under Lollipop, but OnDateChanged() does get called and mDate does change if the DatePicker is in Spinners mode. Under earlier versions of Android, OnDateChanged() gets called and mDate gets changed in both versions of the DatePicker.
Is there any way to get a CalendarView DatePicker in 5.0 to call OnDateChanged()? Failing that, how else can I retrieve a changed date from the DatePicker when it's in CalendarView mode?
I face the same issue and the thing is onDateChange() and onTimeSet() listeners for DatePicker and TimePicker is not called in Nexus devices with lollipop Update.
The reason is in nexus devices, since the clock app is updated, the listeners are not working.
The work around is once the dialog dismiss, you need to create you own listener and set the values in a calendar object using the datepicker get() methods and pass the calendar to the listener.
A simple sample code is
/**
* Returns the calendar instance once the date and time is set.
* #return
*/
public Calendar getDateTime() {
mCalendar.set(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
timePicker.getCurrentHour(),
timePicker.getCurrentMinute());
return mCalendar;
}
Set this in your Xml-Layout:
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:spinnersShown="false"
android:id="#+id/datepicker_popupwindow"/>
With "android:spinnersShown="false" " you tell it to not show the Spinner. But it will call the 'onDateChanged' Method.

How to stop the Date Picker Dialogue-box Date to set the previous Dates. It should allow only above System current date date

Hi every one thanks in advance..
I have requirement in my App that I have a Date Picker to set the date. Now I want to restrict the Date Picker to set the date above System current dates but not below to the System current date. How....?
Can any one help me out from this.... And How to validate the System current date with the Date Picker Date.
In this case you can extend DatePickerDialog and make your own implementation of OnDateChanged, which is called everytime that the date changes and you get as parameters the DatePicker, and the new year, month and day values, so you can check if that date is past and in that case throw the error (with a Toast or whatever) and call DatePicker.updateDate() to set a correct value (so that DatePicker is allways in a consistent state).
Also, you can call to DatePicker.init(year, monthOfYear, dayOfMonth, onDateChangedListener); then you can pass a
onDateChangedListener implementation without having to extend DatePickerDialog.
EDIT: (I never try this but I think it can done your work..)
DatePicker's
setMinDate(long minDate)
Sets the minimal date supported by this NumberPicker in milliseconds since January 1, 1970 00:00:00 in getDefault() time zone.
Example:
DatePickerDialog dialog = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
dialog.getDatePicker().setMinDate(new Date());
Use setMinDate function of CalendarView class. Here you can set your date in milli seconds. To prevent future dates use setMaxDate
Use getDatePicker to get the datepicker and set calendarView as told above.
private int myear; //Declare these three variables in MainActivity and call showDialog(1)
private int mmonth;
private int mday;
final Calendar myCalendar= Calendar.getInstance();
private void setCurrentDateOnView() { //Call this method before showDialog
myear = myCalendar.get(Calendar.YEAR);
mmonth = myCalendar.get(Calendar.MONTH);
mday = myCalendar.get(Calendar.DAY_OF_MONTH);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
DatePickerDialog startDate = new DatePickerDialog(this, datePickerListener, myear,mmonth,
mday){
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
}
};
myCalendar.set(myear, mmonth, mday);
long startTime = myCalendar.getTimeInMillis();
startDate.getDatePicker().setMinDate(startTime - 1000);
return startDate;
}
return null;
}

Categories

Resources