How to implement Android date picker in a fragment - java

I have implemented a date picker as following.
private void updateDisplay() {
String str_date = "";
if ((Month + 1) >= 10) {
if (Day < 10) {
str_date = Year + "-" + (Month + 1) + "-0" + Day;
} else {
str_date = Year + "-" + (Month + 1) + "-" + Day;
}
} else {
if (Day < 10) {
str_date = Year + "-0" + (Month + 1) + "-0" + Day;
} else {
str_date = Year + "-0" + (Month + 1) + "-" + Day;
}
}
date.setText("" + str_date);
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(Year, Month, Day);
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(viewLoad.getContext(),
mDateSetListener, Year, Month, Day);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Year = year;
Month = monthOfYear;
Day = dayOfMonth;
updateDisplay();
}
};
Here is my code segment for button.
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnDate:
showDialog(DATE_DIALOG_ID);
break;
This works fine. Now the problem is I need to implement a date picker in a fragment. Can anyone plz explain how to do it.
Edited Code
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Year = year;
Month = monthOfYear;
Day = dayOfMonth;
updateDisplay();
}
};
Thanx in advance.

Use this CustomDialogFragment that contains use of
TimePicker Dialog fragment
DatePicker Dialog fragment
Simple Dialog Fragment
CustomeDialogFragment Class
public class CustomDialogFragment extends DialogFragment
{
public static final int DATE_PICKER = 1;
public static final int TIME_PICKER = 2;
public static final int DIALOG = 3;
Context mContext;
String mMessage;
boolean finishActivity;
// private Fragment mCurrentFragment;
Activity mActivity;
/**
* this constructor is used for datepicker & Timepicker
*/
public CustomDialogFragment (Fragment fragment ) {
// mCurrentFragment = fragment;
}
public CustomDialogFragment (Activity mActivity ) {
this.mActivity = mActivity;
}
/**
* this constructor is used for simple dialog fragment
*/
public CustomDialogFragment(Context context, String message, final boolean finishActivity) {
mContext = context;
mMessage = message;
this.finishActivity = finishActivity;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bundle = new Bundle();
bundle = getArguments();
int id = bundle.getInt("dialog_id");
switch (id) {
case DATE_PICKER:
return new DatePickerDialog(getActivity(),
(OnDateSetListener)mActivity, bundle.getInt("year"),
bundle.getInt("month"), bundle.getInt("day"));
case TIME_PICKER:
return new TimePickerDialog(getActivity(),
(OnTimeSetListener)mActivity,bundle.getInt("hour"),
bundle.getInt("minute"), true);
case DIALOG:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle(R.string.app_name);
alertDialogBuilder.setMessage(mMessage);
alertDialogBuilder.setIcon(R.drawable.ic_launcher);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(
getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
if (finishActivity == true) {
Activity act = (Activity) mContext;
act.finish();
}
}
});
alertDialogBuilder.setNegativeButton(getResources().getString(R.string.cancel_btn_title), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
CustomDialogFragment.this.dismiss();
}
});
return alertDialogBuilder.create();
}
//Define your custom dialog or alert dialog here and return it.
return new Dialog(getActivity());
}
}
& Use date Picker this Way
1) In your Activity Or fragment Implement OnDateSetListener ( after done it will get back result to onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) method)
2) Call DatePicker From Fragment Like this way
CustomDialogFragment dialog = new CustomDialogFragment(YourFragment.this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", CustomDialogFragment.DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);
dialog.show(getFragmentManager(), "dialog");
& Call DatePicker From Activity(or FragmentActivity) Like this Way
CustomDialogFragment dialog = new CustomDialogFragment(this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", CustomDialogFragment.DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);
dialog.setCancelable(false);
dialog.show(this.getSupportFragmentManager(), "dialog");
& as per Set "dialog_id" u can use TIME_PICKER (for time picker dialog) & DIALOG(for simple dialog)
as per send "dialog_id" according to send data through bundle to CustomDialogFragment.

As my knowledge, cannot use showDialog() in Fragment. It's also deprecated.
Use DialogFragment.
Learn from this tutorial as you need
http://www.kylebeal.com/2011/11/android-datepickerdialog-and-the-dialogfragment/

Related

Retrieving times from two TimePickers in DialogFragments

I have an input form in an activity where I'd like to retrieve the start time and end time of an event. I am using a timepicker displayed in a dialog fragment to get the start time and return it to the main activity, but how do re use the same logic to retrieve the end time of the event? My code:
Main Activity:
public class AddEventActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener{
private int pickerHour = 0;
private int pickerMin = 0;
//code ommitted for length
public void showTimePickerDialog(View v) {
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String amOrPm = "am";
pickerHour = hourOfDay;
pickerMin = minute;
String minutesString = "";
if (hourOfDay > 12){ //translate to 12 hr clock. Little workaround to get both timepicker and am/pm label to show up correctly.
amOrPm = "pm";
pickerHour-=12;
}
if (pickerMin < 10) {
minutesString = "0"; //fix weird bug where only one zero is shown on times ending in :00
}
startTimeView.setText(pickerHour + " : " + minutesString + pickerMin + " " +amOrPm );
}
TimePickerFragment:
public class TimePickerFragment extends DialogFragment {
int hour,minute;
private Activity mActivity;
private TimePickerDialog.OnTimeSetListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
try {
mListener = (TimePickerDialog.OnTimeSetListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnTimeSetListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(mActivity, mListener, hour, minute,
DateFormat.is24HourFormat(mActivity));
}
}
I need to be able to differentiate between the start time and the end time, but I am not sure how to differentiate them without repeating myself. I am pretty new to Java and Android. Thank you so much for any help.
Possibly something as simple as a boolean?
public class AddEventActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener{
...
boolean isSettingStartTime = true;
//code ommitted for length
public void showTimePickerDialog(View v) {
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
...
if (isSettingStartTime) {
startTimeView.setText(pickerHour + " : " + minutesString + pickerMin + " " +amOrPm );
isSettingStartTime = false;
} else {
endTimeView.setText(pickerHour + " : " + minutesString + pickerMin + " " +amOrPm );
}
}
}
This would require you being able to retrieve the TimePicker from your TimePickerFragment
You either need to get the TimePicker instance when you create both TimePickerFragments and store them in two fields such as startTimePicker and finishTimePicker.
Then when the TimePicker is passed in through the onTimeSet you then check to see which TimePicker it is like so.
if ( timePicker == startTimePicker ) {
startTimeTextView.setText....
} else {
finishTimeTextView.setText...
}

Don't understand how to correct mistake in datepicker code

I am not able to understand where am I doing mistake. I want to check it is a weekend or weekday. If it is weekend then it should prompt in the toast that it is a sunday or saturday weekend. I don't know what should I put in place of ??? mark. It should also display current date if it is weekend. Please, any one can help me. Thank you.
View.OnClickListener//,
// TimePickerDialog.OnTimeSetListener
// 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());
/*
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
x_year = calendar.get(Calendar.YEAR);
*/
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:
break;
}
}
private void setupTime(int hours, int minutes) {
views.button_time.setText(hours + ":" + minutes);
}
private void setupDate(int day, int month, int year) {
String strMonth = ((month + 1) <= 9) ? ("0" + (month + 1)) : String.valueOf(month + 1);
views.button_date.setText(String.valueOf(day) + "/" + strMonth + "/" + String.valueOf(year));
}
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) {
Calendar c = Calendar.getInstance();
// c.setTime();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek == 7 || dayOfWeek == 1) {
// as your requirement: you should display mesage 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();
}
}
}
}
Once you get your date you can do like this and get the day and proceed with your logic.
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
I think that your variable dayOfWeek is the same variable as the parameter dayOfMonth
The above code must work
public DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
if (selectedDay == 1 || selectedDay == 7) {
Toast.makeText(DateTimePickerActivity.this
, "You have selected weekend"
, Toast.LENGTH_SHORT).show();
view.updateDate(selectedYear,selectedMonth,selectedDay);
}
}
};

SimpleDateFormat and wrong dates

I had already tried the first two suggestions below, but I tried again and sincerely thanks for the help! The result is the same though. I´ll just edit the post to add more code info.
Hello there! I´m experimenting with a simple ToDo application and managed to change almost everything I wanted besides the date formatted that´s displayed once the user saves the task.
The task itself is added via the AddToDoActivity class which has the following resumed code:
public class AddToDoActivity extends Activity {
// 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000
private static final int SEVEN_DAYS = 604800000;
private static final String TAG = "Lab-UserInterface";
private static String timeString;
private static String dateString;
private static TextView dateView;
private static TextView timeView;
private Date mDate;
private RadioGroup mPriorityRadioGroup;
private RadioGroup mStatusRadioGroup;
private EditText mTitleText;
private RadioButton mDefaultStatusButton;
private RadioButton mDefaultPriorityButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo);
mTitleText = (EditText) findViewById(R.id.title);
mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone);
mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority);
mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
dateView = (TextView) findViewById(R.id.date);
timeView = (TextView) findViewById(R.id.time);
// Set the default date and time
setDefaultDateTime();
// OnClickListener for the Date button, calls showDatePickerDialog() to show
// the Date dialog
final Button datePickerButton = (Button) findViewById(R.id.date_picker_button);
datePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
// OnClickListener for the Time button, calls showTimePickerDialog() to show
// the Time Dialog
final Button timePickerButton = (Button) findViewById(R.id.time_picker_button);
timePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
}
});
// OnClickListener for the Cancel Button,
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
finish();
}
});
//OnClickListener for the Reset Button
final Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered resetButton.OnClickListener.onClick()");
setDefaultDateTime();
mTitleText.setText("");
mDefaultStatusButton.setChecked(true);
mDefaultPriorityButton.setChecked(true);
}
});
// OnClickListener for the Submit Button
// Implement onClick().
final Button submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered submitButton.OnClickListener.onClick()");
// Gather ToDoItem data
Priority priority = getPriority();
Status status = getStatus();
String titleString = mTitleText.getText().toString();
// Date
String fullDate = dateString + " " + timeString;
// Package ToDoItem data into an Intent
Intent data = new Intent();
ToDoItem.packageIntent(data, titleString, priority, status, fullDate);
setResult(Activity.RESULT_OK, data);
finish();
}
});
}
// Do not modify below here
// Use this method to set the default date and time
private void setDefaultDateTime() {
// Default is current time + 7 days
mDate = new Date();
mDate = new Date(mDate.getTime() + SEVEN_DAYS);
Calendar c = Calendar.getInstance();
c.setTime(mDate);
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH),
c.get(Calendar.YEAR));
dateView.setText(dateString);
setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
c.get(Calendar.MILLISECOND));
timeView.setText(timeString);
}
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
// Increment monthOfYear for Calendar/Date -> Time Format setting
monthOfYear++;
String mon = "" + monthOfYear;
String day = "" + dayOfMonth;
if (monthOfYear < 10)
mon = "0" + monthOfYear;
if (dayOfMonth < 10)
day = "0" + dayOfMonth;
dateString = year + "-" + mon + "-" + day;
}
private static void setTimeString(int hourOfDay, int minute, int mili) {
String hour = "" + hourOfDay;
String min = "" + minute;
if (hourOfDay < 10)
hour = "0" + hourOfDay;
if (minute < 10)
min = "0" + minute;
timeString = hour + ":" + min + ":00";
}
private Priority getPriority() {
switch (mPriorityRadioGroup.getCheckedRadioButtonId()) {
case R.id.lowPriority: {
return Priority.LOW;
}
case R.id.highPriority: {
return Priority.HIGH;
}
default: {
return Priority.MED;
}
}
}
private Status getStatus() {
switch (mStatusRadioGroup.getCheckedRadioButtonId()) {
case R.id.statusDone: {
return Status.DONE;
}
default: {
return Status.NOTDONE;
}
}
}
// DialogFragment used to pick a ToDoItem deadline date
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int dayOfMonth, int monthOfYear,
int year) {
setDateString(dayOfMonth, monthOfYear, year);
dateView.setText(dateString);
}
}
// DialogFragment used to pick a ToDoItem deadline time
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return
return new TimePickerDialog(getActivity(), this, hour, minute,
true);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTimeString(hourOfDay, minute, 0);
timeView.setText(timeString);
}
}
private void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
private void showTimePickerDialog() {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
Here´s the ToDoItem, that actually reads the info from AddToDoActivity:
public class ToDoItem {
public static final String ITEM_SEP = System.getProperty("line.separator");
public enum Priority {
LOW, MED, HIGH
};
public enum Status {
NOTDONE, DONE
};
public final static String TITLE = "title";
public final static String PRIORITY = "priority";
public final static String STATUS = "status";
public final static String DATE = "date";
public final static String FILENAME = "filename";
public final static SimpleDateFormat FORMAT = new SimpleDateFormat(
"dd/MM/yyyy HH:mm:ss", Locale.US);
private String mTitle = new String();
private Priority mPriority = Priority.LOW;
private Status mStatus = Status.NOTDONE;
private Date mDate = new Date();
ToDoItem(String title, Priority priority, Status status, Date date) {
this.mTitle = title;
this.mPriority = priority;
this.mStatus = status;
this.mDate = date;
}
// Create a new ToDoItem from data packaged in an Intent
ToDoItem(Intent intent) {
mTitle = intent.getStringExtra(ToDoItem.TITLE);
mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY));
mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS));
try {
mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE));
} catch (ParseException e) {
mDate = new Date();
}
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority priority) {
mPriority = priority;
}
public Status getStatus() {
return mStatus;
}
public void setStatus(Status status) {
mStatus = status;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
// Take a set of String data values and
// package them for transport in an Intent
public static void packageIntent(Intent intent, String title,
Priority priority, Status status, String date) {
intent.putExtra(ToDoItem.TITLE, title);
intent.putExtra(ToDoItem.PRIORITY, priority.toString());
intent.putExtra(ToDoItem.STATUS, status.toString());
intent.putExtra(ToDoItem.DATE, date);
}
public String toString() {
return mTitle + ITEM_SEP + mPriority + ITEM_SEP + mStatus + ITEM_SEP
+ FORMAT.format(mDate);
}
public String toLog() {
return "Title:" + mTitle + ITEM_SEP + "Priority:" + mPriority
+ ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:"
+ FORMAT.format(mDate);
}
}
Oh well, after hours tweaking the
public final static SimpleDateFormat FORMAT = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US);
method from ToDoItem, I still cannot successfully convert yyyy-MM-dd to dd/MM/yyyy.
First, I´ve tried the obvious, and changed the expression yyyy-MM-dd to dd/MM/yyyy.
After that, all I got after saving the task was today´s date, even though the date inputted on AddToDoActivity is months or years ahead. If I revert back to yyyy-MM-dd, the date shown on the Task List is the same inputted on AddToDoActivity.
Then I tried to change all mentions of dates on every class to match the exact format that I wanted.
That made everything look good on AddToDoActivity, but again, when I transported the date back to ToDoItem, the app just ignored the previously inputted date and showed today´s date again.
Can anyone help me with this one??
Thanks!!
You are calling setDateString with arguments in the order of year, month, day:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
But your method has parameters in the order of day, month, year:
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
...
}
I also think you made some errors while copying your code into the question, since the setDateString method is duplicated and there is no setTimeString method.
Change:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
to:
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
Modify the code as follows in the ToDoListAdapter file getView method
// TODO - Display Time and Date.
// Hint - use ToDoItem.FORMAT.format(toDoItem.getDate()) to get date and time String
final TextView dateView = (TextView) itemLayout.findViewById(R.id.dateView);
dateView.setText(ToDoItem.FORMAT.format(toDoItem.getDate()));
The output will be something similar the the following
Reference:
Completing UI Activity assignment

how to update edittext on datepicker set button [duplicate]

This question already exists:
edittext not updated when set new date
Closed 9 years ago.
this is my code which work fine updare edittext but problem is edittext not update imediately until i click again on edittext tell me how do i update edittext on datepicker dailog (positive button) h date picker display two default button positive and negative how do i update editteext on positive button help me please
EditText edtKeyword;
String selectedDate;
int mYear,mMonth,mDay ;
DateFormat fmtDateAndTime = DateFormat.getDateInstance();
Calendar myCalendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
edtKeyword.setClickable(true);
edtKeyword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(MenuList.this, d, myCalendar
.get(Calendar.YEAR),
myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
mYear = myCalendar.get(Calendar.YEAR);
mMonth = myCalendar.get(Calendar.MONTH);
mDay = myCalendar.get(Calendar.DAY_OF_MONTH);
selectedDate= mMonth+"-"+mDay+"-"+mYear;
edtKeyword.setText(selectedDate);
}
});
edtKeyword.setText(fmtDateAndTime.format(myCalendar.getTime()));
I tried this code. It works fine for me. Please try it once
private int pYear = 1970;
private int pMonth = 1;
private int pDay = 1;
static final int DATE_DIALOG_ID = 0;
Then in onCreate:
edt_birth.setKeyListener(null);
edt_birth.setOnTouchListener(new OnTouchListener() {
#SuppressWarnings("deprecation")
#Override
public boolean onTouch(View v, MotionEvent event) {
showDialog(DATE_DIALOG_ID);
return false;
}
});
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, pDateSetListener, pYear, pMonth,
pDay);
}
return null;
}
private DatePickerDialog.OnDateSetListener pDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
pYear = year;
pMonth = monthOfYear;
pDay = dayOfMonth;
updateDisplay();
}
};
private void updateDisplay() {
int temp = pMonth + 1;
edt_birth.setText(pDay + "/" + temp + "/" + pYear);
}
This will update your edittext.

why does my code set values to the wrong view with listener

I have four Buttons that display the the date/time of calendars which are attributes of my activity. When a button is pressed, the according DatePickerDialog gets called which sets the values the users entered in the calendar object.
Though the identification of the calendars and dialogs seems correct, when I press "endDate" and click on ok in the dialog, startDate's text gets set.
Why does android behave like this and to fix this nonsense behaviour? (And yes, I cleaned and refreshed the project...)
Thank's in advance, you always surprise me guys :)
UPDATE
OK, now I got it, I set the MONTH in the onTimeSetListener fr startDate instead of the MINUTE; fixed the code
/UPDATE
Here's the listing:
this is a part of the attribute definition (I left out the Views)
static final int START_DATE_DIALOG_ID = 0;
static final int START_TIME_DIALOG_ID = 1;
static final int END_DATE_DIALOG_ID = 2;
static final int END_TIME_DIALOG_ID = 3;
this is the relevant part of the onCreate()
startDate = (Button)findViewById(R.id.startDate);
startTime = (Button)findViewById(R.id.startTime);
endDate = (Button)findViewById(R.id.endDate);
endTime = (Button)findViewById(R.id.endTime);
startCal = Calendar.getInstance();
endCal = Calendar.getInstance();
[......]
startDate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(START_DATE_DIALOG_ID);
}
});
startTime.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(START_TIME_DIALOG_ID);
}
});
endDate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(END_DATE_DIALOG_ID);
}
});
endTime.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(END_TIME_DIALOG_ID);
}
});
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case START_DATE_DIALOG_ID:
return new DatePickerDialog(this,
startDateSetListener,
startCal.get(Calendar.YEAR),
startCal.get(Calendar.MONTH),
startCal.get(Calendar.DAY_OF_MONTH));
case START_TIME_DIALOG_ID:
return new TimePickerDialog(this,
startTimeSetListener,
startCal.get(Calendar.HOUR_OF_DAY),
startCal.get(Calendar.MINUTE),
true); // is24hView
case END_DATE_DIALOG_ID:
return new DatePickerDialog(this,
endDateSetListener,
endCal.get(Calendar.YEAR),
endCal.get(Calendar.MONTH),
endCal.get(Calendar.DAY_OF_MONTH));
case END_TIME_DIALOG_ID:
return new TimePickerDialog(this,
endTimeSetListener,
endCal.get(Calendar.HOUR_OF_DAY),
endCal.get(Calendar.MINUTE),
true); // is24hView
}
return null;
}
private DatePickerDialog.OnDateSetListener startDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
startCal.set(Calendar.YEAR, year);
startCal.set(Calendar.MONTH, monthOfYear);
startCal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDisplay(START_DATE_DIALOG_ID);
}
}
;
private DatePickerDialog.OnDateSetListener endDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
endCal.set(Calendar.YEAR, year);
endCal.set(Calendar.MONTH, monthOfYear);
endCal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDisplay(START_DATE_DIALOG_ID);
}
}
;
private TimePickerDialog.OnTimeSetListener startTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
startCal.set(Calendar.HOUR_OF_DAY, hourOfDay);
startCal.set(Calendar.MINUTE, minute);
updateDisplay(START_TIME_DIALOG_ID);
}
}
;
private TimePickerDialog.OnTimeSetListener endTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
endCal.set(Calendar.HOUR_OF_DAY, hourOfDay);
endCal.set(Calendar.MINUTE, minute);
updateDisplay(END_TIME_DIALOG_ID);
}
}
;
// updates the date in the TextView
private void updateDisplay(int dialogId) {
switch(dialogId){
case START_DATE_DIALOG_ID:
startDate.setText(getDateFromCal(startCal));
break;
case START_TIME_DIALOG_ID:
startTime.setText(getTimeFromCal(startCal));
break;
case END_DATE_DIALOG_ID:
endDate.setText(getDateFromCal(endCal));
break;
case END_TIME_DIALOG_ID:
endTime.setText(getTimeFromCal(endCal));
break;
}
}
private String getDateFromCal(Calendar cal){
return new StringBuilder()
.append(cal.get(Calendar.DAY_OF_MONTH)) .append(".")
.append(cal.get(Calendar.MONTH) + 1) .append(".")
.append(cal.get(Calendar.YEAR)) .toString();
}
private String getTimeFromCal(Calendar cal){
StringBuilder sb = new StringBuilder();
int num = cal.get(Calendar.HOUR_OF_DAY);
if(num<10)
sb.append("0");
sb.append(num);
sb.append(":");
num = cal.get(Calendar.MINUTE);
if(num<10)
sb.append("0");
sb.append(num);
return sb.toString();
}
You're updating the wrong display (START_DATE_DIALOG_ID) from your listener endDateSetListener.
private DatePickerDialog.OnDateSetListener endDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
endCal.set(Calendar.YEAR, year);
endCal.set(Calendar.MONTH, monthOfYear);
endCal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDisplay(START_DATE_DIALOG_ID);
}
}
;
Also - may I make a suggestion? It is very rare that a language or library is ever the problem; never assume that it is. Jeff Atwood (one of the guys that started StackOverflow) has an excellent article on the subject: First rule of programming: It's always your fault

Categories

Resources