Open DatePicker with suggested date - java

I need to open a DatePicker with a default date based on the YEAR-MONTH-DAY_OF_MONTH properties of a GregorianCalendar.
Here is the code where I open the DatePicker:
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
For exemple, if my values are like this:
MyCalendar.YEAR = 2017
MyCalendar.MONTH = 2
MyCalendar.DAY_OF_MONTH = 22
The default value set when I open the DatePicker would be:
What do I have to add to do that?

Basically straight from Android | Pickers
Plus, just like any other Fragment, you can use set and get-Arguments to pass data into the fragment.
Details: Best practice for instantiating a new Android Fragment
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static DatePickerFragment newInstance(int year,int month,int day) {
Bundle b = new Bundle();
b.putInt("year", year);
// put others...
Fragment f = new DatePickerFragment();
f.setArguments(b);
return f;
}
#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);
// Update using the arguments
Bundle args = getArguments();
if (args != null) {
year = args.getInt("year");
// get others...
}
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
And use that newInstance method.
DialogFragment newFragment = DatePickerFragment.newInstance(2017,02,07);
newFragment.show(getFragmentManager(), "datePicker");

Related

Waiting for TimePickerFragment to return time

New to JAVA and Android coding and trying my first practical project.
I don't understand how to make processing wait until timekeeperdialog returns a value.
In my Main Activity I have created getters and setters to variables (first time doing this btw):
private int pickhour;
private int pickminute;
public MainActivity(){
pickhour = 0;
pickminute = 0;
}
public void setpickhour(int pickhour) {
this.pickhour = pickhour;
}
public int getpickhour(){
return this.pickhour;
}
public void setpickminute(int pickminute) {
this.pickminute = pickminute;
}
public int getPickminute(int pickminute) {
return this.pickminute;
}
I call the dialog box with this, and then expecting processing to pause until the TimePicker returns a value, I have a Toast to show results. The Toast fires as soon as the Timepicker appears.
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(),"TimePicker");
Toast.makeText(getApplicationContext(), "Time Picker" + String.valueOf(pickhour) + ":" + String.valueOf(pickminute), Toast.LENGTH_LONG).show();
And my fragment looks like this :
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
private MainActivity ma = new MainActivity();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
//Use the current time as the default values for the time picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
//Create and return a new instance of TimePickerDialog
return new TimePickerDialog(getActivity(),this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
//onTimeSet() callback method
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
//Do something with the user chosen time
//Get reference of host activity (XML Layout File) TextView widget
ma.setpickhour(hourOfDay);
ma.setpickminute(minute);
}
}
I tried looping through a boolean set by the ontimeset method to force waiting on a return value, but my application just hung.
What fundamental concept am I missing? I'm on vacation, so spent a day & a half trying to figure this out.
You can try this -
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener{
private MainActivity ma = new MainActivity();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
//Use the current time as the default values for the time picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
//Create and return a new instance of TimePickerDialog
return new TimePickerDialog(getActivity(),this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
//onTimeSet() callback method
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
//Do something with the user chosen time
//Get reference of host activity (XML Layout File) TextView widget
ma.setpickhour(hourOfDay);
ma.setpickminute(minute);
Toast.makeText(getApplicationContext(), "Time Picker" + String.valueOf(pickhour) + ":" + String.valueOf(pickminute), Toast.LENGTH_LONG).show();
}
}
And if you are only using fragment for timePicker there is no need of the fragment.
In this case you can try this in MainActivity -
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
cal.set(Calendar.MINUTE, minute);
setpickhour(hourOfDay);
setpickminute(minute);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Time Picker");
mTimePicker.show();
Does your code work? Because you cannot pass "this" as second argument in TimePickerDialog constructor.

How to get date from Calendar [duplicate]

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Closed 5 years ago.
I have another class which showing calendar to user and setup date in textview. But how to get date (year from here? for calculate how old year user in general).
This is code which I'm using. This is: TextViewDatePicker editTextDatePicker = new TextViewDatePicker implement class which shows calendar for user and setup date in text view. I don't know ho to setup this date for this code: Calendar dateOfYourBirth = new GregorianCalendar();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_fragment);
editTextForAge = (TextView) findViewById(R.id.ed_calendar);
Window window = this.getWindow();
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(ProfileGeneral.this, editTextForAge);
Calendar dateOfYourBirth = new GregorianCalendar();
Calendar today = Calendar.getInstance();
int yourAge = today.get(Calendar.YEAR) - dateOfYourBirth.get(Calendar.YEAR);
dateOfYourBirth.add(Calendar.YEAR, yourAge);
if (today.before(dateOfYourBirth)) {
yourAge--;
}
And this is class which showing calendar for user:
public class TextViewDatePicker
implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
public static final String DATE_SERVER_PATTERN = "yyyy-MM-dd";
private DatePickerDialog mDatePickerDialog;
private TextView mView;
private Context mContext;
private long mMinDate;
private long mMaxDate;
public TextViewDatePicker(Context context, TextView view) {
this(context, view, 0, 0);
}
public TextViewDatePicker(Context context, TextView view, long minDate, long maxDate) {
mView = view;
mView.setOnClickListener(this);
mView.setFocusable(false);
mContext = context;
mMinDate = minDate;
mMaxDate = maxDate;
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
Date date = calendar.getTime();
SimpleDateFormat formatter = new SimpleDateFormat(DATE_SERVER_PATTERN);
mView.setText(formatter.format(date));
}
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
mDatePickerDialog = new DatePickerDialog(mContext, this, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
if (mMinDate != 0) {
mDatePickerDialog.getDatePicker().setMinDate(mMinDate);
}
if (mMaxDate != 0) {
mDatePickerDialog.getDatePicker().setMaxDate(mMaxDate);
}
mDatePickerDialog.show();
}
This goes a lot easier with java.time, the modern Java date and time API.
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// date picker month is 0-based, so add 1 to it
LocalDate datePickerDate = LocalDate.of(year, monthOfYear + 1, dayOfMonth);
mView.setText(datePickerDate.toString());
LocalDate today = LocalDate.now(ZoneId.of("America/Tortola"));
long yourAge = ChronoUnit.YEARS.between(datePickerDate, today);
}
Can you use this on Android? Certainly! For most Android devices you will need to get ThreeTenABP, the backport of java.time from Java 8 to Android Java 7. It is all well explained in this question: How to use ThreeTenABP in Android Project (that is ThreeTen for JSR-310, where java.time wsa first described, and ABP for Android Backport).
Please substitute your desired time zone if it doesn’t happen to be America/Tortola.
You used wrong constructor for TextViewDatePicker
Update code :
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(ProfileGeneral.this, editTextForAge);
with
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(ProfileGeneral.this, editTextForAge,0,0);

datepickerdialog hide calendar and change my date picker view to standard mode

I want to change my date picker view to standard mode
From
To
My code is
dateOfBirthET = (EditText) findViewById(R.id.dateOfBirth);
//setting dateSetListener
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
updateLabelToSave();
}
};
//setting onClickListener on setDate
dateOfBirthET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatePickerDialog dpd = new DatePickerDialog(RegisterActivity.this, date,
myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH));
//setting maxDate on tempCal
long maxDate = new Date().getTime();
tempCal.setTimeInMillis(maxDate);
tempCal.set(Calendar.YEAR, tempCal.get(Calendar.YEAR) - 16);
dpd.getDatePicker().setMaxDate(tempCal.getTimeInMillis());
dpd.show();
}
});
}
I am tried this code also but not working
dpd.getDatePicker().setCalendarViewShown(false);
You just need to change theme you want while creating DatePickerDialog instance
DatePickerDialog dpd = new DatePickerDialog(RegisterActivity.this, android.R.style.Theme_Holo_Dialog ,date,
myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH));
Working for me tested android 6.0 marshmallow.
From the setCalendarViewShown doc it says
Calling this method has no effect when the DatePicker_datePickerMode
attribute is set to calendar.
And as of Android L, with the Material theme selected, the default layout of android:datePickerMode is calendar (see here)
So if you want to change your DatePickerDialog to spiner style, you must change android:datePickerMode
And now I see datePickerMode can not change programmatically, it can only change by config XML like
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
/>
Therefore I think you should create a custom your DatePickerDilog layout

Unable to call object method

I'm working on an android app. That uses a 'datepicker' as part of a data entry form. I've written a getter method "onDateSet" to return data from the object but i'm unable to call the method from the instance of the class.
line: datePicker.getSelectedDate(); I'm getting a 'method cannot be resolved' error
I get the same message when I try and access the variable directly. datePicker.selecteddate
I would be grateful if someone could point me in the right direction.
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);
}
int selectedDate;
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
selectedDate = day+month+year;
}
public int getSelectedDate() {
return selectedDate;
}
}
public void showDatePickerDialog(View view) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getFragmentManager(), "datePicker");
int output = datePicker.getSelectedDate();
}
You have:
DialogFragment datePicker = new DatePickerFragment();
You mean:
DatePickerFragment datePicker = new DatePickerFragment();
This is because your methods are members of your subclassed DatePickerFragment, not of the base class DialogFragment.
Essentially, when you refer to an object through its base type, the compiler only knows about the methods the base type declares. It has no way of knowing that an arbitrary DialogFragment is actually a DatePickerFragment (or any other derived type).
An alternative, if you know it is a DatePickerFragment, is to explicitly cast datePicker to a DatePickerFragment:
DialogFragment datePicker = new DatePickerFragment();
...
int output = ((DatePickerFragment)datePicker).getSelectedDate();
This, of course, will fail with a ClassCastException if datePicker isn't actually a DatePickerFragment.

DateFormat produces incorrect output

I've got a couple of Buttons that initially display the current date and the current time, respectively. When clicking in the Button that displays the date, it shows a DatePickerFragment that allows the user to choose a date, and then changes the Button's text to the date selected by the user. The other Button does exactly the same but with a TimePickerFragment.
To initialize the Buttons I use the following code:
protected void onCreate(Bundle savedInstanceState){
...
df = DateFormat.getDateInstance();
tf = DateFormat.getTimeInstance();
initDate = new GregorianCalendar();
...
updateDateButtons();
updateTimeButtons();
}
private void updateTimeButtons() {
tf.setCalendar(initDate);
String text = tf.format(initDate.getTime());
btnIniTime.setText(text.substring(0, text.lastIndexOf(":")));
}
private void updateDateButtons() {
df.setCalendar(initDate);
btnIniDate.setText(df.format(initDate.getTime()));
}
Initially, both buttons behave in an expected manner: btnIniTime shows the current time, and btnIniDate shows the current date.
As I said, when the user clicks the btnIniTime button, it shows a TimePickerFragment that prompts the user to choose a time, and the selected time is correctly displayed in btnIniTime.
The problem starts with btnIniDate, that should do the same, but using a DatePickerFragment instead of a TimePickerFragment. When the user selects a date, the button then displays an incorrect date. For example, if I choose 2013 Aug 30, the displayed date turns to be 2013 Aug. 26. If I choose 2013 Sep 1, it then shows 2013 Sep 29!
The classes and methods that I use to change the date ara arranged in the following way:
public abstract static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
protected TaskActivity activity;
protected Calendar c;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (TaskActivity) activity;
}
#Override
public abstract Dialog onCreateDialog(Bundle savedInstanceState);
public void onDateSet(DatePicker view, int year, int month, int day) {
if(activity instanceof TaskActivity){
setDateResult(year, month, day);
}
}
protected abstract void setDateResult(int year, int month, int day);
}
public static class InitDatePickerFragment extends DatePickerFragment {
#Override
protected void setDateResult(int year, int month, int day) {
activity.setInitDate(year, month, day);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = activity.getInitDate();
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);
}
}
...
public Calendar getInitDate() {
return initDate;
}
public void setInitDate(int year, int month, int day){
Log.d("TaskActivity", "Year: " + year + "; Month: " + month + "; Day: " + day);
initDate.set(Calendar.YEAR, year);
initDate.set(Calendar.MONTH, month);
initDate.set(Calendar.DAY_OF_WEEK, day);
updateDateButtons();
}
When you push the button:
#Override
public void onClick(View v) {
if(v.equals(btnIniDate)){
DialogFragment newFragment = new InitDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "initDatePicker");
}
...
}
By the way, when setting the date, LogCat produces the following output (I've chosen 2013 Aug 30):
Year: 2013; Month: 7; Day:30
The Problem might be
initDate.set(Calendar.DAY_OF_WEEK, day);
in your setInitDate(). This updates only the day of the week. So your date jumps +-6
use
initDate.set(Calendar.DAY_OF_MONTH, day);

Categories

Resources