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));
}
};
Related
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();
}
}}
});
}
}
I'm trying to set a minimum date (which is supposed to be the current date) so that the user won't be able to select a date older than today. I'm working in a fragment as you can see. I already searched for help but either it wasn't clear to me since i'm just starting with coding or i just failed to use it. Here is what i coded until now but i can't go further.
public 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 datePicker, int year, int month, int day) {
Calendar cal = new GregorianCalendar(year, month, day);
setDate(cal);
}
protected void setDate(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
((TextView) getActivity().findViewById(R.id.datenaissance)).setText(dateFormat.format(calendar.getTime()));
}
}
Here is the second fragment i'm working with:
package cm.opep.opep.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import cm.opep.opep.R;
public class RegistrationFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_registration, container, false);
initUI(v);
return v;
}
private void initUI(View v){
//Lancement de la date de naissance
EditText datenaissance = (EditText) v.findViewById(R.id.datenaissance);
datenaissance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatePickerFragment fragment = new DatePickerFragment();
fragment.show(getFragmentManager(), "datePicker");
}
});
}
}
Here's the XML code:
<LinearLayout xmlns
android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white"
tools:context="cm.opep.opep.Tiroir$PlaceholderFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="UselessParent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/datenaissance"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:hint="#string/date_de_naissance"
android:inputType="date"
android:textColor="#color/colorPrimaryDark"
android:textSize="12sp"
android:onClick="datePicker"
android:focusable="False"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Any help will be appreciated. Thanks
All you need to do is create an instance of DatePickerDialog and using the 'set min date()' function.
public 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
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
// Here you can set the minimum date on date picker ********
dialog.getDatePicker().setMinDate(new Date().getTime());
return dialog;
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
Calendar cal = new GregorianCalendar(year, month, day);
setDate(cal);
}
protected void setDate(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
((TextView) getActivity().findViewById(R.id.datenaissance)).setText(dateFormat.format(calendar.getTime()));
}
}
or you can use this class:
public class StartDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener {
Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);
SharedPreferences objSharedPreferences;
SharedPreferences.Editor objEditor;
private Activity activity;
private View component;
public StartDatePicker(Activity activity, View component) {
this.activity = activity;
this.component = component;
createSharedPreferences();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Use the current date as the default date in the picker
DatePickerDialog dialog = new DatePickerDialog(activity, this, startYear, startMonth, startDay);
// dialog.getDatePicker().setMaxDate(new Date().getTime());
// dialog.getDatePicker().setMinDate(new Date().getTime());
return dialog;
}
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
try {
startDay = dayOfMonth;
startMonth = monthOfYear + 1;
startYear = year;
String dateToBeSet = startDay + "-" + getMonth(startMonth) + "-" + startYear;
if (component instanceof EditText) {
((EditText) component).setText(dateToBeSet);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month - 1].substring(0, 3);
}
}
On editText click use this code :
DialogFragment dialogFragment = new StartDatePicker(this, fromDateEditText);
dialogFragment.show(getFragmentManager(), "start_date_picker");
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.
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(" "));
}
};
}
Good day, can't seem to find a solution for this. i have 2 buttons that when pressed, opens a datepickerdialog, but my problem now is , how can i set them to the appropriate button on OnDateSet method. I am using a DialogFragment for the date and then implementing the DateListener in my activity. I have tried using getTag() but no success in getting the tag. here is what i tried:
public void showfromDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "fromdatePicker");
}
public void showtoDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "todatePicker");
}
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
if(view.getTag().toString().equals("fromdatePicker")) { // error here
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
if(view.getTag() == "todatePicker") {
todate.setText(text);
}
any ideas how to implement this? i keep seeing solutions about using 2 different DialogFragment class but am guessing there should be another way. or am i wrong? Thank you
ok, i have a work around for these. which can be helpful for anyone with this problem. if its slightly incorrect please let me know and i can change it. but this is what i did to solve this issue.
in on DateSet:
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
FragmentManager fragmanager = getSupportFragmentManager();
if(fragmanager.findFragmentByTag("fromdatePicker") != null) {
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
// if(view.getTag() == "todatePicker") {
if(fragmanager.findFragmentByTag("todatePicker") != null) {
todate.setText(text);
}
that way you can use the same dateListener for multiple calls and set the date appropriately based on the tag that was passed when calling show on the dialog.
Use below code of DatePicker Dialog.
private int mYear;
private int mMonth;
private int mDay;
Calendar cal4DatePicker = Calendar.getInstance();
Button btnDOB=findviewbyId(R.id.btndob);
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
cal4DatePicker.set(Calendar.YEAR, mYear);
cal4DatePicker.set(Calendar.MONTH, mMonth);
cal4DatePicker.set(Calendar.DAY_OF_MONTH, mDay);
btnDOB.setText(new StringBuilder()
.append(mDay).append("-").append(mMonth).append("-").append(mYear).append(" "));
}
};
on btnDOB you need to set click listner to show this DatePicker Dialog.
I have try same thing with Time Picker only. You can try out and set same for date picker also.
package com.example.toolboxtest;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends FragmentActivity implements OnClickListener {
Button testBtn;
EditText testET;
static final int TIME_DIALOG_ID = 0;
int mHour = 0;
int mMinute = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testBtn = (Button) findViewById(R.id.testBTn);
testET = (EditText) findViewById(R.id.testET);
testBtn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.testBTn:
showDialog(TIME_DIALOG_ID);
break;
}
}
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour=hourOfDay;
mMinute = minute;
// myPrefs = ImportantDateReminderActivity.this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
// prefsEditor = myPrefs.edit();
// prefsEditor.putInt("hour", mHour);
// prefsEditor.putInt("minute", mMinute);
// prefsEditor.putString("a", a);
// prefsEditor.commit();
if(mHour==12){
//reminderSetTime.setText(new StringBuilder().append("12").append(":").append((minute)+" PM"));
testET.setText(mHour+":"+mMinute+" "+"PM");
}
else
updateTimeDisplay();
}
};
private void updateTimeDisplay() {
try {
Format formatter;
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
Date d = df.parse(mHour + ":" + mMinute);
Calendar gc = new GregorianCalendar();
gc.setTime(d);
//gc.add(Calendar.HOUR, 0);
Date d2 = gc.getTime();
formatter = new SimpleDateFormat("hh:mm a");
String time = formatter.format(d2);
System.out.println("The TIME is: "+time);
testET.setText(time);
String hour = new SimpleDateFormat("hh").format(d2);
String minute = new SimpleDateFormat("mm").format(d2);
String a = new SimpleDateFormat("a").format(d2);
System.out.println("The Hour is: "+hour+ " "+minute+ " " +a);
/*myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
prefsEditor = myPrefs.edit();
prefsEditor.putInt("hour", Integer.parseInt(hour));
prefsEditor.putInt("minute", Integer.parseInt(minute));
prefsEditor.putString("a", a);
prefsEditor.putString("complateTime", time);
prefsEditor.commit();*/
//addTwoMonthNotification();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,mTimeSetListener, mHour, mMinute, false);
}
return null;
}
}
Hope it will help you.
Please let me know if there is any issue.