In here 'onClickListner' on 'Image Button' my custom 'DatePickerFragment' is displaying to select the date. Below is the code for
DatePickerFragment.java
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.DatePicker;
import java.util.Calendar;
/**
* Created by Admin on 9/4/18.
*/
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
private onDatePickerListener mListener;
private boolean future;
public DatePickerFragment(){
}
// public DatePickerFragment(boolean future){
// this.future=future;
// }
#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);
Log.d("DATE_PICKER", " CURRENT_MONTH " + month);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.AppBaseTheme,this, year, month, day);
if(isFuture() ==false){
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
}
// Create a new instance of DatePickerDialog and return it
return datePickerDialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
callListener(year, month, day);
}
public DialogFragment setCallbackListener(onDatePickerListener listener) {
mListener = listener;
return null;
}
private void callListener(int year, int month, int day) {
if (mListener != null) mListener.onDataSet(year, month, day);
}
public boolean isFuture() {
return future;
}
public void setFuture(boolean future) {
this.future = future;
}
public interface onDatePickerListener {
void onDataSet(int year, int month, int day);
}
}
Then I call this 'Fragment' in my 'MainActivity' to set the date to 'EditText' when click on the 'OK' button from the 'DatePickerFragment'.
MainActivity.java
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.sample.DatePickerFragment;
public class AddInterestedKarmaActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_interested_karma);
ButterKnife.bind(this);
context = this;
EditText dateEdittext = (Edittext)findViewById(R.id.date_edit);
setDate(dateEditText);
}
private void setDate(final EditText dateEditText){
datePickerFragment.setCallbackListener(new DatePickerFragment.onDatePickerListener() {
#Override
public void onDataSet(int year, int month, int day) {
int currentMonth = 0;
if (month == 0) {
currentMonth = 1;
} else if (month == 1) {
currentMonth = 2;
} else if (month == 2) {
currentMonth = 3;
} else if (month == 3) {
currentMonth = 4;
} else if (month == 4) {
currentMonth = 5;
} else if (month == 5) {
currentMonth = 6;
} else if (month == 6) {
currentMonth = 7;
} else if (month == 7) {
currentMonth = 8;
} else if (month == 8) {
currentMonth = 9;
} else if (month == 9) {
currentMonth = 10;
} else if (month == 10) {
currentMonth = 11;
} else if (month == 11) {
currentMonth = 12;
} else if (month == 12) {
}
dateEditText.setText(day + "/" + currentMonth + "/" + year);
}
});
}
DialogFragment datePicker = datePickerFragment;
datePicker.show(getSupportFragmentManager(), "datePicker");
}
private void setTime(final EditText timeEditText){
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
String curTime = String.format("%02d:%02d", hourOfDay, minute);
timeEditText.setText(curTime);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
}
I need to set the Date of 'DatePickerFragmenet' for a custom date (not today). such as set the 'DatePickerFragment' onCreate() to the mentioned above final int y, m, d values that from 'dateEditText'. And also I need to set the custom 'time' to the 'TimePickerDialog' such as 'DatePickerFragment'.
There is one function in DatePickerDialog to set custom date(updateDate(year_, month_, day_))
According to your code you need to make changes in your DatePickerFragment
in onCreateDialog of DatePickerFragment where you are getting date, month and year from calendar, instead of getting that from Calendar provide your custom dates.
Updated class is below
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
private onDatePickerListener mListener;
private boolean future;
int day_;
int month_;
int year_;
private DatePickerDialog datePickerDialog;
public DatePickerFragment() {
}
#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);
// Log.d("DATE_PICKER", " CURRENT_MONTH " + month);
// int day = c.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(getActivity(), R.style.AppTheme, this, year_, month_, day_);
if (isFuture() == false) {
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
}
// datePickerDialog.updateDate(year_, month_, day_);
// Create a new instance of DatePickerDialog and return it
return datePickerDialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
callListener(year, month, day);
}
public DialogFragment setCallbackListener(onDatePickerListener listener) {
mListener = listener;
return null;
}
private void callListener(int year, int month, int day) {
if (mListener != null) mListener.onDataSet(year, month, day);
}
public boolean isFuture() {
return future;
}
public void setFuture(boolean future) {
this.future = future;
}
public interface onDatePickerListener {
void onDataSet(int year, int month, int day);
}
}
In your activity, you need to provide custom date.
Updated Activity is below, you can add your custom date.
public class AddInterestedKarmaActivity extends AppCompatActivity {
DatePickerFragment datePickerDialog;
EditText dateEdittext;
String customDate = "12/12/2007"; //dd/mm/yy
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_interested_karma);
dateEdittext = (EditText) findViewById(R.id.date_edit);
// setDate(dateEditText);
datePickerDialog = new DatePickerFragment();
datePickerDialog.day_ = getDay();
datePickerDialog.month_ = getMonth();
datePickerDialog.year_ = getYear();
datePickerDialog.setCallbackListener(new DatePickerFragment.onDatePickerListener() {
#Override
public void onDataSet(int year, int month, int day) {
month = month + 1;
dateEdittext.setText(day + "/" + month + "/" + year);
}
}
);
datePickerDialog.show(getSupportFragmentManager(), "datePicker");
}
private int getYear() {
return Integer.parseInt(changeDateFormat(customDate, "MM/dd/yyyy", "YYYY"));
}
private int getMonth() {
return Integer.parseInt(changeDateFormat(customDate, "MM/dd/yyyy", "MM")) - 1; //substract one from month because month gets start from 0 in Calendar.
}
private int getDay() {
return Integer.parseInt(changeDateFormat(customDate, "MM/dd/yyyy", "dd"));
}
public String changeDateFormat(String dateString, String sourceDateFormat, String targetDateFormat) {
if (dateString == null || dateString.isEmpty())
return "";
SimpleDateFormat inputDateFromat = new SimpleDateFormat(sourceDateFormat, Locale.US);
Date date = new Date();
try {
date = inputDateFromat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outputDateFormat = new SimpleDateFormat(targetDateFormat, Locale.US);
return outputDateFormat.format(date);
}
}
Related
Calendar calender = Calendar.getInstance();
final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(LabCheckOutActivity.this,
myDateListener, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
calender.get(Calendar.DAY_OF_MONTH)+1);
pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
pickerDialog.show();
by Using this code, in dialog date is pointed to tomorrow but user can also select todays date.I want user can select date from tomorrow not today.
public class CustomDatePickerDialog extends DatePickerDialog {
int maxYear;
int maxMonth;
int maxDay;
public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
}
public void setMaxDate(long maxDate) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getDatePicker().setMaxDate(System.currentTimeMillis());
} else {
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(maxDate);
maxYear = c.get(Calendar.YEAR);
maxMonth = c.get(Calendar.MONTH);
maxDay = c.get(Calendar.DAY_OF_MONTH);
}
}
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
super.onDateChanged(view, year, monthOfYear, dayOfMonth);
} else {
if (year > maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (monthOfYear > maxMonth && year == maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
view.updateDate(maxYear, maxMonth, maxDay);
}
}
}
Use
pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()+24*60*60*1000);//where 24*60*60*1000 represents the total timestamp for one day
instead of
pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
Please see complete implementation below:
DialogFragment class
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
public DatePickerFragment()
{
}
public void setiDateTimeListener(IDateTimeListener iDateTimeListener)
{
this.iDateTimeListener = iDateTimeListener;
}
#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);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
// Set minimum date as tommorw
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() + 24*60*60*1000);
// If need to set max date then use this also
// datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
// Create a new instance of DatePickerDialog and return it
return datePickerDialog;
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
try
{
String selectedDt = dayOfMonth+"-"+(monthOfYear + 1)+"-"+year;
iDateTimeListener.onDateSet(selectedDt);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Interface must be implemented in date picker calling class
public interface IDateTimeListener
{
public void onDateSet(String date);
}
Calling dialog fragment
public void showDatePickerDialog()
{
DatePickerFragment datePickerFragment = new DatePickerFragment();
datePickerFragment.setiDateTimeListener(this);
datePickerFragment.show(getActivity().getSupportFragmentManager(),"datePicker");
}
if (CustomVerticalCalendarView.isPreviousDateDisabled()) { // disable previous date disable flow
int daysOfYear = listCalender.get(Calendar.DAY_OF_YEAR);
int currentDate = today.get(Calendar.DAY_OF_YEAR);
int listYear = listCalender.get(Calendar.YEAR);
int currentYear = today.get(Calendar.YEAR);
if (daysOfYear < currentDate || listYear < currentYear) {
checkBox.setEnabled(false);
checkBox.setTextColor(ContextCompat.getColor(checkBox.getContext(), R.color.dark_gray));
}
}
Hope this code helps you.
I am doing datepicker. I am facing some challenges. I am checking wheather selected date is weekend or not. If it is weekend then it should give current date only. Now I don't know where should I put condition in this program and how to get the day of the week and against which thing I should check.
Please, help me.
// TimePickerDialog.OnTimeSetListener
{
//Declaration for class
ButtonViews views;
dpListener dpListenerView;
// Declartion for member vairables
int day, month, x_year;
int hour;
int minute;
Calendar calendar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
views = new ButtonViews();
dpListenerView = new dpListener();
//ButtonListener
views.button_date.setOnClickListener(this);
views.button_time.setOnClickListener(this);
//
// pick up the default date using Calender class
calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
curr_date();
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
setupDate(day, month, x_year);
setupTime(hour, minute);
}
public void curr_date(){
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
x_year = calendar.get(Calendar.YEAR);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_date:
showDatePickerDialog();
break;
case R.id.button_time:
/* showTimePickerDialog();*/
break;
}
}
private void setupTime(int hours, int minutes) {
views.button_time.setText(hours + ":" + minutes);
}
private void setupDate(int day, int month, int year) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
String strMonth = ((month + 1) <= 9) ? ("0" + (month + 1)) : String.valueOf(month + 1);
views.button_date.setText(String.valueOf(day) + "/" + strMonth + "/" + String.valueOf(year));
String strDate = String.valueOf(day) + "/" + strMonth + "/" + String.valueOf(year);
Date d = null;
try {
d = (Date) sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
calendar.setTime(d);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek == 7 || dayOfWeek == 1) {
Toast.makeText(DateTimePickerActivity.this,"You have chosen weekend",Toast.LENGTH_SHORT);
}
}
private void showDatePickerDialog() {
DatePickerDialog datepickerdialog = new DatePickerDialog
(
this,
dpListenerView,
/* new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
} },*/
//this,
x_year,
month,
day
);
datepickerdialog.show();
}
class ButtonViews {
Button button_time;
Button button_date;
public ButtonViews() {
button_date = (Button) findViewById(R.id.button_date);
button_time = (Button) findViewById(R.id.button_time);
}
}
class dpListener implements OnDateSetListener {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
setupDate(dayOfMonth, monthOfYear, year);
/* if(dayOfWeek == 7 || dayOfWeek == 1) {*/
// as your requirement: you should display message they can not select the weekend" here
// then you set the value in datepickerdialog by current date
// Toast.makeText(DateTimePickerActivity.this
// , "You have selected weekend ", Toast.LENGTH_SHORT).show();
// }
}
}
}
I am using datepickerdialog. it run properly on kitkat but when i run application on lollipop and when i click on edit text it opens a datepickerdialog box but when i select date it give unfortunately stop error. Below is the code for datepicker on edittext.
private void setDateTimeField() {
fromLabel.setOnClickListener(this);
toLabel.setOnClickListener(this);
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); //yyyy/MM/dd HH:mm:ss
final Date date = new Date();
final String u = dateFormat.format(date);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
from1 = dateFormatter.format(newDate.getTime());
diff1 = newDate.getTimeInMillis();
long d = date.getTime();
if((newDate.getTime()).equals(date)||(newDate.getTime()).after(date)){
long d1 = (diff1 / (24 * 60 * 60 * 1000) - d / (24 * 60 * 60 * 1000)) + 1;
if(d1>30){
total.setVisibility(View.VISIBLE);
total.setText("Booking not allowed as the Date given is outside Advance Booking Period");
avail.setVisibility(View.GONE);
}
else{
total.setVisibility(View.GONE);
fromLabel.setText(from1);
toLabel.setText(null);
to=null;
avail.setVisibility(View.GONE);
from=fromLabel.getText().toString();
}
}
else{
total.setVisibility(View.VISIBLE);
total.setText("Choose date after or equals to current date");
fromLabel.setText("");
toLabel.setText(null);
from=null;
to=null;
}
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
fromDatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.Done), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
dialog.cancel();
if(type.equals("According to time"))
{
int cnt=-1;
if(from1.equals(u)){
cnt = 1;
loadTimeSpinnerDataATT(text,from,cnt);
}
else if(total.getText()=="Choose date after or equals to current date")
{
}
else if(total.getText()=="Booking not allowed as the Date given is outside Advance Booking Period")
{
}
else
{cnt = 0;
loadTimeSpinnerDataATT(text,from,cnt);
}
}
}
}
});
}
public void onClick(View view) {
if(view == fromLabel) {
fromDatePickerDialog.show();
} else if(view == toLabel) {
toDatePickerDialog.show();
}
}
public void onClose(DialogInterface dialogInterface)
{
}
}
Try it, may help you,
Date picker error resloved here
Link For Date picker
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
// for date picker
EditText m3_DateDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m3_DateDisplay = (EditText) findViewById(R.id.datepick);
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Show selected date
StringBuilder dateValue1 = new StringBuilder().append(day).append("-")
.append(month + 1).append("-").append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
testDate1 = sdf123.parse(abs1);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
m3_DateDisplay.setText(DateFormat);
m3_DateDisplay.setFocusable(false);
m3_DateDisplay.setInputType(InputType.TYPE_NULL);
m3_DateDisplay.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
// return new DatePickerDialog(this, pickerListener, year, month,
// day);
// ///Only Show till Date Not More than That.
DatePickerDialog dialog = new DatePickerDialog(this,
pickerListener, year, month, day);
dialog.getDatePicker().setMaxDate(new Date().getTime());
return dialog;
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
StringBuilder dateValue = new StringBuilder().append(day)
.append("-").append(month + 1).append("-").append(year)
.append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue.toString();
Date testDate1 = null;
try {
testDate1 = sdf123.parse(abs1);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
m3_DateDisplay.setText(DateFormat);
}
};
}
change minimum api-11 in manifest
I am working on a project which has a sign up form where there is a field for date of birth.So i tried using datepicker control .But it was hard setting the maximum and minimum dates in the control .Also versions prior to honeycomb work differently from versions after honeycomb.The following is the code i used.
The main class:
package com.example.datepickercustom;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btndate;
TextView txtdate;
private int intCurrentYear;
private int intCurrentMonth;
private int intCurrentDay;
private int intMaxYear;
private int intMaxMonth;
private int intMaxDay;
private int intMinYear;
private int intMinDay;
private int intMinMonth;
private int year;
private int month;
private int day;
private static final int MILLIS_IN_SECOND = 1000;
private static final int SECONDS_IN_MINUTE = 60;
private static final int MINUTES_IN_HOUR = 60;
private static final int HOURS_IN_DAY = 24;
private static final int DAYS_IN_YEAR = 365;
static final int DATE_PICKER_ID = 1111;
GregorianCalendar calendar;
DatePicker mDatePickerInstance;
DatePickerDialogWithMaxMinRange datePickerDialog= null;
DatePickerDialog.OnDateSetListener datePickerOnDateSetListener;
Calendar myCalendar;
DatePickerDialog dpd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btndate=(Button) findViewById(R.id.btndate);
txtdate=(TextView) findViewById(R.id.txtdate);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show current date
txtdate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
}
else
{
setDate();
}
btndate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
showDialog(DATE_PICKER_ID);
}
else
{
datePickerDialog.show();
}
}
});
}
#SuppressLint("NewApi")
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
final long MILLISECONDS_IN_YEAR =
(long)MILLIS_IN_SECOND * SECONDS_IN_MINUTE * MINUTES_IN_HOUR
* HOURS_IN_DAY * DAYS_IN_YEAR;
Calendar now = Calendar.getInstance();
calendar=new GregorianCalendar();
int current_year=now.get(Calendar.YEAR);
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
dpd=new DatePickerDialog(this, pickerListener, year, month,day);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//Calendar.getInstance().get(Calendar.YEAR)-19
dpd.getDatePicker().setMaxDate((current_year-16-1970)*MILLISECONDS_IN_YEAR);
dpd.getDatePicker().setMinDate((current_year-100-1970)*MILLISECONDS_IN_YEAR);
}
return dpd;
}
return null;
}
public void setDate() {
/*
* Initialise Listener for date set
*/
txtdate.setText(new StringBuilder().append(year)
.append("-").append(month + 1).append("-")
.append(day));
datePickerOnDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
txtdate.setText(new StringBuilder().append(year)
.append("-").append(monthOfYear + 1).append("-")
.append(dayOfMonth));
}
};
// initialise DatePicker
myCalendar = Calendar.getInstance();
intCurrentYear = myCalendar.get(Calendar.YEAR);
intCurrentMonth = myCalendar.get(Calendar.MONTH);
intCurrentDay = myCalendar.get(Calendar.DAY_OF_MONTH);
intMaxYear = intCurrentYear-18;
intMaxMonth = intCurrentMonth;
intMaxDay = intCurrentDay;
intMinYear = intCurrentYear-100;
intMinMonth = intCurrentMonth;
intMinDay = intCurrentDay;
datePickerDialog = new DatePickerDialogWithMaxMinRange(
this, datePickerOnDateSetListener,intMinYear,intMinMonth,intMinDay,intMaxYear,intMaxMonth,intMaxDay);
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
txtdate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
The custom class for versions prior to honeycomb:
package com.example.datepickercustom;
import android.app.DatePickerDialog;
import android.content.Context;
import android.widget.DatePicker;
public class DatePickerDialogWithMaxMinRange extends DatePickerDialog {
static int maxYear=2005;
static int maxMonth=11;
static int maxDay=31;
int minYear=1955;
int minMonth=0;
int minDay=1;
public DatePickerDialogWithMaxMinRange(Context context, OnDateSetListener callBack,int minYear,int minMonth,int minDay,int maxYear,int maxMonth,int maxDay) {
super(context,callBack, maxYear, maxMonth, maxDay);
this.minDay = minDay;
this.minMonth = minMonth;
this.minYear = minYear;
DatePickerDialogWithMaxMinRange.maxDay = maxDay;
DatePickerDialogWithMaxMinRange.maxMonth = maxMonth;
DatePickerDialogWithMaxMinRange.maxYear = maxYear;
}
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
super.onDateChanged(view, year, monthOfYear, dayOfMonth);
if (year > maxYear ||monthOfYear > maxMonth && year == maxYear||
dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth){
view.updateDate(maxYear, maxMonth, maxDay);
}else if(year < minYear ||monthOfYear < minMonth && year == minYear||
dayOfMonth < minDay && year == minYear && monthOfYear == minMonth){
view.updateDate(minYear, minMonth, minDay );
}
}
}
My question is that the above appears long and hard for setting date of birth.Is there a better of doing the above?
DatePicker has setMinDate and setMaxDate methods. It's very easy to set minimum and maximum dates with them.
What do you mean under this?:
versions prior to honeycomb work differently from versions after
honeycomb
Of cause there's difference. DatePicker matches current Android version and there should be difference as well as for any control.
you can use 3rd party libraries for presenting a calendar view and then on click you can choose the desired date.I have used the time square lib for same purpose and is very nice.take a look HERE.
There is another good library check THIS
use them in a dialog and cancel the dialog when you are done picking the date.As mentioned you can also show the view within any date range you want.So you can set a max and min date.Just have to read the usage properly and its easy and effective
Hi am using Date picker in more than three class with same validation. Instead I must write in one class and call that function in other classes when I required, is it possible Below code for Date picker.
public class MainActivity extends Activity {
private TextView tvDisplayDate;
private Button btnChangeDate;
private int myear;
private int mmonth;
private int mday;
static final int DATE_DIALOG_ID = 999;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentDateOnView();
addListenerOnButton();
}
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
final Calendar c = Calendar.getInstance();
myear = c.get(Calendar.YEAR);
mmonth = c.get(Calendar.MONTH);
mday = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(mmonth + 1).append("-").append(mday).append("-")
.append(myear).append(" "));
}
public void addListenerOnButton() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
DatePickerDialog _date = new DatePickerDialog(this, datePickerListener, myear,mmonth,
mday)
{
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year < myear)
view.updateDate(myear, mmonth, mday);
if (monthOfYear < mmonth && year == myear)
view.updateDate(myear, mmonth, mday);
if (dayOfMonth < mday && year == myear && monthOfYear == mmonth)
view.updateDate(myear, mmonth, mday);
}
};
return _date;
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
myear = selectedYear;
mmonth = selectedMonth;
mday = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(mmonth + 1)
.append("-").append(mday).append("-").append(myear)
.append(" "));
Date dateObject1 = new Date(myear - 1900, mmonth, mday);
Date dateObj2 = new Date(System.currentTimeMillis());
if(dateObject1.before(dateObj2) || dateObject1.equals(dateObj2)){
//the program runs normally
}
else{
new AlertDialog.Builder(MainActivity.this)
.setTitle("Wrong Data Input!")
.setMessage("The end Date must be Before the start Date, please insert new Date values")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
};
}
You could have a DateUtils class with a static method, which takes in the dates, along with the context. This method can do the date validations and build the AlertDialog accordingly. You can call this static method this way.
DateUtils.dateValidator(Date, Context);
This can be called in the onDateSet() of your OnDateSetListener for each DatePicker.