Android datepicker disable all dates prior to 1st dec 2014 - android

i have successfully implemented datepicker in android my problem is i want to disable all dates in datepicker prior to 1 st dec 2014 how can that be done ,i tried looking for examples but they all provide examples to disable date prior to todays date
i have not implemented any code for disabling previous dates any working example would be good
thanks in advance
here is my code
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
/** Private members of the class */
private TextView pDisplayDate;
private Button pPickDate;
private int pYear;
private int pMonth;
private int pDay;
/** This integer will uniquely define the dialog to be used for displaying date picker.*/
static final int DATE_DIALOG_ID = 0;
/** Callback received when the user "picks" a date in the dialog */
private DatePickerDialog.OnDateSetListener pDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
pYear = year;
pMonth = monthOfYear + 1;
pDay = dayOfMonth;
// if (pMonth<10)
// pMonth='0'+pMonth;
// if (pDay<10)
// pDay='0'+pDay;
updateDisplay();
displayToast();
}
};
/** Updates the date in the Te
* xtView */
private void updateDisplay() {
String formattedMonth = "" + pMonth;
String formattedDayOfMonth = "" + pDay;
if(pMonth < 10){
formattedMonth = "0" + pMonth;
}
if(pDay < 10){
formattedDayOfMonth = "0" + pDay;
}
// searchText.setText(formattedDayOfMonth + "/" + formattedMonth + "/" + year);
pDisplayDate.setText(
new StringBuilder()
// // Month is 0 based so add 1
.append(pYear).append("-")
.append(formattedMonth).append("-")
.append(formattedDayOfMonth).append(" "));
}
/** Displays a notification when the date is updated */
private void displayToast() {
Toast.makeText(this, new StringBuilder().append("Date choosen is ").append(pDisplayDate.getText()), Toast.LENGTH_SHORT).show();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Capture our View elements */
pDisplayDate = (TextView) findViewById(R.id.displayDate);
pPickDate = (Button) findViewById(R.id.pickDate);
/** Listener for click event of the button */
pPickDate.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
/** Get the current date */
final Calendar cal = Calendar.getInstance();
pYear = cal.get(Calendar.YEAR);
pMonth = cal.get(Calendar.MONTH);
pDay = cal.get(Calendar.DAY_OF_MONTH);
/** Display the current date in the TextView */
updateDisplay();
}
/** Create a new dialog for date picker */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
pDateSetListener,
pYear, pMonth, pDay);
}
return null;
}
}

set Max date like this :
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
DatePickerDialog dialog = new DatePickerDialog(mContext,
datePickerListener, myCalendar.get(Calendar.YEAR),
myCalendar.get(Calendar.MONTH), myCalendar
.get(Calendar.DAY_OF_MONTH));
dialog.getDatePicker().setMaxDate(new Date().getTime());
dialog.show();
}
return null;
}

done it might be helpful for someone can play with the if conditions accordingly
package com.example.datepicker;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
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 {
private TextView tvDisplayDate;
private Button btnChangeDate;
private int myear;
private int mmonth;
private int mday;
private int maxyear;
private int maxmonth;
private int maxday;
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();
maxyear = c.get(Calendar.YEAR);
maxmonth = c.get(Calendar.MONTH);
maxday = c.get(Calendar.DAY_OF_MONTH);
myear = 2014;
mmonth = 12;
mday = 31;
String formattedMonth = "" + mmonth;
String formattedDayOfMonth = "" + mday;
// set selected date into textview
if(maxmonth < 10){
formattedMonth = "" + maxmonth + 1;
}
if(maxday < 10){
formattedDayOfMonth = "0" + maxday;
}
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(formattedMonth).append("-").append(formattedDayOfMonth).append("-")
.append(maxyear).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, maxyear,maxmonth,
maxday){
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year < 2014)
view.updateDate(2014, mmonth, mday);
if (monthOfYear < 12 && year == 2014)
view.updateDate(2014, 12, mday);
if (dayOfMonth < 31 && year == 2014 && monthOfYear == 12)
view.updateDate(2014, 12, 31);
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);
}
};
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;
String formattedMonth = "" + mmonth;
String formattedDayOfMonth = "" + mday;
// set selected date into textview
if(mmonth < 10){
formattedMonth = "" + mmonth + 1;
}
if(mday < 10){
formattedDayOfMonth = "0" + mday;
}
tvDisplayDate.setText(new StringBuilder().append(formattedMonth)
.append("-").append(formattedDayOfMonth).append("-").append(myear)
.append(" "));
}
};
}

Related

How do I find days between two date pickers in android? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Android Days between two dates
(19 answers)
How to calculate number of days between two datepicker in android and display in the edit text
(3 answers)
Closed 2 years ago.
I have been trying to find the difference between two dates from date picker. My app is getting crashed for null point object exception.
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
package com.cksapp.dateformat;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static java.util.Calendar.YEAR;
public class MainActivity extends AppCompatActivity {
TextView t1, t2, t3, t4, difference;
Button b1;
Date datefrom, dateOne;
Date dateto, dateTwo;
Date d1, d2;
private DatePickerDialog.OnDateSetListener mDate1;
private DatePickerDialog.OnDateSetListener mDate2;
private Object Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = findViewById(R.id.textView);
t2 = findViewById(R.id.textView2);
t3 = findViewById(R.id.textView3);
t4 = findViewById(R.id.textView4);
difference = findViewById(R.id.textView7);
b1 = findViewById(R.id.button);
t1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
int year = c.get(YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(MainActivity.this,
android.R.style.Theme_Holo_Dialog_MinWidth,
mDate1,
year,month,day);
//Date dateOne = c.getTime();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDate1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String datefrom = month + "/" + dayOfMonth + "/" + year;
t2.setText(datefrom);
}
};
//next
t3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
int year = c.get(YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(MainActivity.this,
android.R.style.Theme_Holo_Dialog_MinWidth,
mDate2,
year,month,day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDate2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String dateto = month + "/" + dayOfMonth + "/" + year;
t4.setText(dateto);
}
};
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This is where I tried performing subtraction but it didn't work
long diff = dateto.getTime() - datefrom.getTime();
difference.setText((int) diff);
}
});
}
}
By putting String in front of dateto, you've made it a declaration of a local variable rather than a reference to the instance variable (that you're trying to access later). So it will forever be null. Change:
String dateto = month + "/" + dayOfMonth + "/" + year;
to
dateto = new Date(month, dayOfMonth, year); // no "String"
However, the Date constructor is deprecated and using Date is strongly discouraged, so you should really use something like:
import java.time.LocalDate;
import java.time.Instant;
import java.time.ZoneOffset;
//...
Instant dateto;
//...
LocalDate localDate = LocalDate.of(month, dayOfMonth, year);
dateto = localDate.atStartOfDay(ZoneOffset.UTC).toInstant();
Never mind, I figured out the answer using joda library
I have made it with different UI, joda library dependancy is included in build.gradle. It worked perfect.
package com.cksapp.newdateformat;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import net.danlew.android.joda.JodaTimeAndroid;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import static org.joda.time.Days.daysBetween;
public class MainActivity extends AppCompatActivity {
TextView t1, t2, t3, t4, today;
Button b1, b2, b3;
String date1, date2, todaydate;
int daysy, daysm, daysd, daysss;
DatePickerDialog.OnDateSetListener dateSetListener;
DatePickerDialog.OnDateSetListener dateSetListener2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JodaTimeAndroid.init(this);
today = findViewById(R.id.today);
t1 = findViewById(R.id.starttext);
t2 = findViewById(R.id.endtext);
t3 = findViewById(R.id.daystext);
t4 = findViewById(R.id.daysinyears);
b1 = findViewById(R.id.startbutton);
b2 = findViewById(R.id.endbutton);
b3 = findViewById(R.id.calculatebutton);
Calendar c = Calendar.getInstance();
final int year = c.get(Calendar.YEAR);
final int month = c.get(Calendar.MONTH);
final int day = c.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
todaydate = sdf.format(Calendar.getInstance().getTime());
today.setText("Today is " + todaydate);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(v.getContext(),dateSetListener,year,month,day);
datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
datePickerDialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
date1 = dayOfMonth + "/" + month + "/" + year;
t1.setText(date1);
}
};
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog2 = new DatePickerDialog(v.getContext(),dateSetListener2,year,month,day);
datePickerDialog2.getDatePicker().setMaxDate(new Date().getTime());
datePickerDialog2.show();
}
});
dateSetListener2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
date2 = dayOfMonth + "/" + month + "/" + year;
t2.setText(date2);
}
};
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(date1 == null || date2 == null){
Toast.makeText(getApplicationContext(), "Please enter the date field(s)",Toast.LENGTH_SHORT).show();
}
else {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
try {
Date d1 = sdf1.parse(date1);
Date d2 = sdf1.parse(date2);
long fromdate = d1.getTime();
long todate = d2.getTime();
Period p = new Period(fromdate, todate, PeriodType.yearMonthDay());
int years = p.getYears();
int months = p.getMonths();
int days = p.getDays();
t4.setText(years + " years" + months + " months" + days + " days");
int diff = (int) (d2.getTime() - d1.getTime());
int YO = diff/86400000;
//Log.d("Days", String.valueOf(diff));
t3.setText(String.valueOf(YO));
} catch (ParseException e) {
e.printStackTrace();
}
}}
});
}
}

Time Picker Minimum Time

I am using TimePicker for selecting time, and I want to set minimum time in picker to limit user from choosing past time.Is there any way to achieve that?
Create a xml file and name it activity_time_picker.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TimePicker
android:id="#+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/layoutHourMinute"
android:layout_centerInParent="true"
/>
</RelativeLayout>
Now create activity class like this
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.NumberPicker;
import android.widget.TimePicker;
public class TimePickerActivity extends Activity {
TimePicker timePicker;
private int TIME_PICKER_INTERVAL = 15;
NumberPicker minutePicker;
List<String> displayedValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_time_picker);
super.onCreate(savedInstanceState);
timePicker = (TimePicker)findViewById(R.id.timePicker1);
timePicker.setIs24HourView(true);
timePicker.setCurrentHour(0);
timePicker.setCurrentMinute(0);
setTimePickerInterval(timePicker);
}
#SuppressLint("NewApi")
private void setTimePickerInterval(TimePicker timePicker) {
try {
Class<?> classForid = Class.forName("com.android.internal.R$id");
// Field timePickerField = classForid.getField("timePicker");
Field field = classForid.getField("minute");
minutePicker = (NumberPicker) timePicker
.findViewById(field.getInt(null));
minutePicker.setMinValue(0);
minutePicker.setMaxValue(3);
displayedValues = new ArrayList<String>();
for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
displayedValues.add(String.format("%02d", i));
}
// for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
// displayedValues.add(String.format("%02d", i));
// }
minutePicker.setDisplayedValues(displayedValues
.toArray(new String[0]));
minutePicker.setWrapSelectorWheel(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hey use this create a DatePicker fragment as below :
public class DatePickerFragment1 extends DialogFragment {
DatePickerDialog.OnDateSetListener ondateSet;
private int year, month, day;
public DatePickerFragment1() {}
public void setCallBack(DatePickerDialog.OnDateSetListener ondate) {
ondateSet = ondate;
}
#SuppressLint("NewApi")
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
year = args.getInt("year");
month = args.getInt("month");
day = args.getInt("day");
}
#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);
DatePickerDialog dpd = new DatePickerDialog(getActivity(),AlertDialog.THEME_DEVICE_DEFAULT_LIGHT,ondateSet,year, month, day);
DatePicker dp = dpd.getDatePicker();
//here it gets the current time and subtracts the time of min date in my case
//I have selected 3months from current time
dp.setMinDate(System.currentTimeMillis() - 5184000000L);
c.add(Calendar.DAY_OF_MONTH, 60);
//current time as max date so it will be displayed as you enter date dialog
dp.setMaxDate(System.currentTimeMillis());
return dpd;
}
}
Then in your fragment or activity call it as :
DatePickerFragment1 date = new DatePickerFragment1();
/**
* Set Up Current Date Into dialog
*/
Calendar calender = Calendar.getInstance();
Bundle args = new Bundle();
args.putInt("year", calender.get(Calendar.YEAR));
args.putInt("month", calender.get(Calendar.MONTH));
args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
date.setArguments(args);
/**
* Set Call back to capture selected date
*/
date.setCallBack(ondate1);
date.show(getActivity().getFragmentManager(), "Date Picker");
}
public String checkDigit(int number) {
return number <= 9 ? "0" + number : String.valueOf(number);
}
DatePickerDialog.OnDateSetListener ondate1 = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
etDatePurchase.setText(String.valueOf(checkDigit(dayOfMonth)) + "/" + String.valueOf(checkDigit(monthOfYear + 1))
+ "/" + String.valueOf(year));
}
};

Can my Date Picker Print my date picked on the EditText not on Toast?

I have this code where when I picked a date it only shows on toast, is there any way for it to be inserted in my EditText? Here is my code.
package com.example.kun.carkila;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
public class RegisterActivity extends AppCompatActivity {
EditText etFirstname, etMiddlename, etLastname, etBirthDate, etAddress, etUsername, etPassword;
Spinner spRole;
int year_x,month_x,day_x;
static final int DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
showDialogOnButtonClick();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void showDialogOnButtonClick(){
etBirthDate = (EditText)findViewById(R.id.etBirthDate);
etBirthDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_ID) {
return new DatePickerDialog(this, dpListener, year_x, month_x, day_x);
}
return null;
}
DatePickerDialog.OnDateSetListener dpListener
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
year_x = year;
month_x = monthOfYear;
day_x = dayOfMonth;
Toast.makeText(RegisterActivity.this, year_x + "/" + month_x + "/" + day_x,Toast.LENGTH_SHORT).show();
}
};
}
And yes I set my EditText clickable to show the datepicker lol. Can i instert the date picked where I can also click on my EditText? Thank you for the help :D
Remove the toast :
Toast.makeText(RegisterActivity.this, year_x + "/" + month_x + "/" + day_x,Toast.LENGTH_SHORT).show();
then set date in edittext :
etBirthDate.setText(year_x + "/" + month_x + "/" + day_x);
This should work
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
year_x = year;
month_x = monthOfYear;
day_x = dayOfMonth;
etBirthDate.setText(year_x + "/" + month_x + "/" + day_x);
}
};

DatePickerDialog showing abnormal behaviour in android 5.1 when timezone is changed

I have to show calender using DatePickerDialog.
The below code is used:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;
import android.widget.Toast;
public class DatePickerExample extends Activity {
private TextView Output;
private Button changeDate;
private Boolean mEnableNativeCalGridView = null;
String timeZone;
public static TimeZone tz;
private int year;
private int month;
DatePickerDialog d;
public Calendar c;
SimpleDateFormat sdf;
private int day;
public static IntentFilter s_intentFilter;
static final int DATE_PICKER_ID = 1111;
static{
s_intentFilter = new IntentFilter();
s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(m_timeChangedReceiver, s_intentFilter);
Output = (TextView) findViewById(R.id.Output);
changeDate = (Button) findViewById(R.id.changeDate);
// sdf = new SimpleDateFormat("EEE, MMM d, ''yy");//Wed, Jul 4, '01
// Show current date
Output.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// Button listener to show date picker dialog
changeDate.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// On button click show datepicker dialog
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_PICKER_ID:
((DatePickerDialog) dialog).updateDate(
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
}
}
#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
sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
c= Calendar.getInstance();
c.setTimeZone(tz);
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
d = new DatePickerDialog(DatePickerExample.this, pickerListener, year, month,day);
setMinMaxdate();
return d;
}
return null;
}
////////////////////Fix for issue on OS 5.1 //////////////////////
public long getDateFormatted(String date){
String givenDateString = date;
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
//////////////////////////////////////////
private DatePicker.OnDateChangedListener newchange= new OnDateChangedListener(){
#Override
public void onDateChanged(DatePicker view,
int year, int monthOfYear,int dayOfMonth) {
Toast.makeText(getApplicationContext(),
"onDateChanged", Toast.LENGTH_SHORT).show();
}};
DatePicker datePicker;
public void setMinMaxdate() {
//Time zone calculation
//TimeZone.setDefault(tz);
///////////////////////
long calEvtEndDate= getDateFormatted("Sun May 31 23:59:59 "+timeZone+" 2015");//System.currentTimeMillis();
long calEvtStartDate= getDateFormatted("Wed May 13 00:00:00 "+timeZone+" 2015");//System.currentTimeMillis()/2;
// long calEvtEndDate = getDateFormatted("Sun, may 31, '15");
//long calEvtStartDate = getDateFormatted("Wed, may 13, '15");
if(d != null){
datePicker = d.getDatePicker();
if(mEnableNativeCalGridView != null){
datePicker.setCalendarViewShown(mEnableNativeCalGridView.booleanValue());
}
// If Start Date is Greater than End Date then we are showing from valid StartDate
// value and we are not setting the maxdate.
if (calEvtStartDate > calEvtEndDate) {
datePicker.setMinDate(calEvtStartDate);
} else {
if (calEvtStartDate > 0) { // If Only ValidStart date is provided, then setting the minDate.
datePicker.setMinDate(calEvtStartDate);
}
if (calEvtEndDate > 0) { // If Only ValidEnd date is provided, then setting the maxDate.
datePicker.setMaxDate(calEvtEndDate);
}
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
System.out.println("-------resumed");
}
public 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) {
//view.updateDate(year, month, day);
System.out.println("---------------datesetchange");
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
Output.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
public void onDestroy() {
super.onDestroy();
unregisterReceiver(m_timeChangedReceiver);
}
private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
System.out.println("timezone changed---"+action.toString());
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
// Intent intent1 = getIntent();
// finish();
// startActivity(intent1);
showDialog(DATE_PICKER_ID);
}
}
};
}
When the app is running, I go to the settings and change the Timezone to such a value so that the current date will change. Now when we select any date in the dialog, it behaves abnormally and goes to other date. I have used setMinDate() and setMaxDate() methods. This happens only in Android OS 5.1.
Any idea or help? Thanks in advance.

Showing Year in DateTimePicker in android

for first time i found the code to show datetimepicker in android (showing year, and month only), but i really confuse how to show only year in my datetime picker, can anyone help me? cause i'm newbie in programming
package com.example.datepicker;
import java.lang.reflect.Field;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
public class MainActivity extends Activity {
static final int DATE_DIALOG_ID = 1;
private int mYear;
private int mMonth;
private int mDay;
private EditText etPickADate;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etPickADate = (EditText) findViewById(R.id.et_datePicker);
etPickADate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
}
DatePickerDialog.OnDateSetListener mDateSetListner = new OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth)
{
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_DIALOG_ID:
/*
* return new DatePickerDialog(this, mDateSetListner, mYear, mMonth,
* mDay);
*/
DatePickerDialog datePickerDialog = this.customDatePicker();
return datePickerDialog;
}
return null;
}
protected void updateDate() {
int localMonth = (mMonth + 1);
String monthString = localMonth < 10 ? "0" + localMonth : Integer
.toString(localMonth);
String localYear = Integer.toString(mYear).substring(2);
etPickADate.setText(new StringBuilder()
// Month is 0 based so add 1
.append(monthString).append("/").append(localYear).append(" "));
showDialog(DATE_DIALOG_ID);
}
private DatePickerDialog customDatePicker()
{
DatePickerDialog dpd = new DatePickerDialog(this, mDateSetListner, mYear, mMonth, mDay);
try {
Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();
for (Field datePickerDialogField : datePickerDialogFields)
{
if (datePickerDialogField.getName().equals("mDatePicker"))
{
datePickerDialogField.setAccessible(true);
DatePicker datePicker = (DatePicker) datePickerDialogField.get(dpd);
Field datePickerFields[] = datePickerDialogField.getType().getDeclaredFields();
for (Field datePickerField : datePickerFields)
{
if ("mDayPicker".equals(datePickerField.getName())||"mDaySpinner".equals(datePickerField
.getName()))
{
datePickerField.setAccessible(true);
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);
}
}
}
}
}
catch (Exception ex)
{}
return dpd;
}
}
and Thank u who can help me :D
To show only year in DatePickerDialog you also need to set Visibility GONE for Month NumberPicker using reflection. do it as:
if ("mDayPicker".equals(datePickerField.getName())
||"mDaySpinner".equals(datePickerField.getName()))
{
datePickerField.setAccessible(true);
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);
}else if("mMonthPicker".equals(datePickerField.getName())){
// to hide month picker
datePickerField.setAccessible(true);
Object monthPicker = new Object();
monthPicker = datePickerField.get(datePicker);
((View) monthPicker).setVisibility(View.GONE);
}

Categories

Resources