I want change the month and year with these two numberpickers but I do not know how to change the date. What I want to do is this: when i click on OK button on BottomSheetDialog I want to set the month and year. Can you help me please? I tried but I couldn't find any solution on the internet. If you help me, I'll be appreciated. Thank you.
public class PlannerFragment extends Fragment implements CalendarAdapter.OnItemListener{
private TextView monthYearTextView;
private TextView monthYearPickerOKTextView;
private ImageView nextMonthImageView, previousMonthImageView;
private RecyclerView calendarRecyclerView;
private LocalDate selectedDate; /// tekrar buna bakılacak
private NumberPicker monthNumberPicker, yearNumberPicker;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle("Planner");
View v = inflater.inflate(R.layout.fragment_planner, container, false);
previousMonthImageView = v.findViewById(R.id.previous_month_image_view);
nextMonthImageView = v.findViewById(R.id.next_month_image_view);
calendarRecyclerView = v.findViewById(R.id.calendar_recycler_view);
monthYearTextView = v.findViewById(R.id.month_year_text_view);
selectedDate = LocalDate.now();
setMonthYear();
previousMonthImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDate = selectedDate.minusMonths(1);
setMonthYear();
}
});
nextMonthImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDate = selectedDate.plusMonths(1);
setMonthYear();
}
});
monthYearTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
monthYearPicker(v);
}
});
return v;
}
private void setMonthYear() {
monthYearTextView.setText(monthYearFromDate(selectedDate));
ArrayList<String> daysInMonth = daysInMonthArray(selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(getActivity(), daysInMonth,
this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
private ArrayList<String> daysInMonthArray(LocalDate date) {
ArrayList<String> daysInMonthList = new ArrayList<>();
YearMonth yearMonth = YearMonth.from(date);
int daysInMonth = yearMonth.lengthOfMonth();
LocalDate firstDayOfMonth = selectedDate.withDayOfMonth(1);
int dayOfWeek = firstDayOfMonth.getDayOfWeek().getValue();
if (dayOfWeek == 7){
dayOfWeek = 1;
} else {
dayOfWeek++;
}
for (int i = 1; i <= 42; i++) {
if (i < dayOfWeek || i >= daysInMonth + dayOfWeek){
daysInMonthList.add("");
} else {
daysInMonthList.add(String.valueOf(i - dayOfWeek + 1));
}
}
return daysInMonthList;
}
private String monthYearFromDate(LocalDate localDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
return localDate.format(formatter);
}
#Override
public void onItemClick(int position, String dayText) {
LocalDate firstDayOfMonth = selectedDate.withDayOfMonth(1);
int dayOfWeek = firstDayOfMonth.getDayOfWeek().getValue();
if (dayOfWeek == 7){
dayOfWeek = 1;
} else {
dayOfWeek++;
}
if (!dayText.equals("")){
/*Toast.makeText(getActivity(), dayText + " " + monthYearFromDate(selectedDate),
Toast.LENGTH_SHORT).show();*/
Toast.makeText(getActivity(), String.valueOf(dayOfWeek),
Toast.LENGTH_SHORT).show();
}
}
public void monthYearPicker(View v){
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getActivity(),
R.style.BottomSheetDialogTheme);
View bottomSheetView = LayoutInflater.from(getActivity())
.inflate(R.layout.month_and_year_picker_bottom_sheet_layout,
(ConstraintLayout) v.findViewById(R.id.month_year_picker_bottom_sheet_container));
monthNumberPicker = bottomSheetView.findViewById(R.id.month_number_picker);
yearNumberPicker = bottomSheetView.findViewById(R.id.year_number_picker);
final Calendar calendar = Calendar.getInstance();
Month.initMonths();
monthNumberPicker.setMinValue(0);
monthNumberPicker.setMaxValue(Month.getMonthArrayList().size() - 1);
monthNumberPicker.setDisplayedValues(Month.monthNames());
monthNumberPicker.setValue(calendar.get(Calendar.MONTH));
yearNumberPicker.setMinValue(1984);
yearNumberPicker.setMaxValue(2040);
yearNumberPicker.setValue(calendar.get(Calendar.YEAR));
bottomSheetView.findViewById(R.id.month_year_picker_ok_text_view).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog.dismiss();
selectedDate.withMonth(monthNumberPicker.getValue());
setMonthYear();
Toast.makeText(getActivity(), Month.getMonthArrayList().get(monthNumberPicker.getValue()).getName(),
Toast.LENGTH_SHORT).show();
}
});
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
}
Good implementation, proper updated answer:
LocalDate date1 = LocalDate.of(2021, Month.JANUARY, 1);
LocalDate date2 = date1.withYear(2010);
LocalDate date3 = date2.withMonth(Month.DECEMBER.getValue());
LocalDate date4 = date3.withDayOfMonth(15);
LocalDate date5 = date4.with(ChronoField.DAY_OF_YEAR, 100);
Stolen from https://kodejava.org/how-do-i-manipulate-the-value-of-localdate-object/
Bad outdated implementation, bad answer (just here for protocol)
Simple pure Java implementation:
Use Calendar. Create a new instance; you probably want Gregorian Calendar: Calendar.getInstance();
Set the calendar value to the date: cal.setTime(pDate);
adjust single fields: cal.add(pField, pValue); or cal.set(pField, pValue);
retrieve Date object: cal.getTime();
You could also use the new java.time package, with classes like LocalDateTime etc.
And then there's a myriad of Java Date Time libraries out there.
Choose the way that works best for you.
This time reminder class, time reminder is crashing on click and erroe goes on "custom.showDialogue" and the error is the following:
FATAL EXCEPTION: main
Process: com.appmetrik.notestakingapp, PID: 18607
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.app.notes.CustomDateTimePicker.showDialog()' on a null object reference
at com.app.notes.AddReminder.onClick(AddReminder.java:261)
public class AddReminder extends AppCompatActivity implements
android.view.View.OnClickListener`{
CustomDateTimePicker custom = null;
TextView txt_Time;
TextView txt_Date;
TextView txt_Day;
EditText et_Reminder_Title;
EditText et_Reminder_Description;
ImageButton btn_Submit_Reminder;
public static String var_Reminder_Title;
public String var_Reminder_Description;
public String var_Reminder_Time;
public String var_Reminder_Date;
public String var_Reminder_Day;
public int var_Not_Day;
public int var_Not_Month;
public int var_Not_Year;
public int var_Not_Hour;
public int var_Not_Min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_reminder);
txt_Time = (TextView) findViewById(R.id.txtEditTime);
txt_Time.setOnClickListener(this);
txt_Date = (TextView) findViewById(R.id.txtEditDate);
txt_Date.setOnClickListener(this);
txt_Day = (TextView) findViewById(R.id.txtEditDay);
txt_Day.setOnClickListener(this);
et_Reminder_Title= (EditText) findViewById(R.id.etEditReminderTitle);
et_Reminder_Description = (EditText) findViewById(R.id.etReminderDescription);
btn_Submit_Reminder = (ImageButton) findViewById(R.id.imgBtnSubmitReminder);
btn_Submit_Reminder.setOnClickListener(this);
try {
custom = new CustomDateTimePicker(AddReminder.this,
new CustomDateTimePicker.ICustomDateTimeListener() {
#Override
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName,
int hour24, int hour12, int min, int sec,
String AM_PM) {
txt_Time.setText(hour12 + ":" + min + " " + AM_PM);
txt_Date.setText(calendarSelected
.get(Calendar.DAY_OF_MONTH)
+ "/" + (monthNumber + 1) + "/" + year);
txt_Day.setText(weekDayFullName);
var_Not_Hour = hour24;
var_Not_Min = min;
var_Not_Month = monthNumber;
var_Not_Day = calendarSelected
.get(Calendar.DAY_OF_MONTH);
var_Not_Year = year;
}
#Override
public void onCancel() {
}
});
/**
* Pass Directly current time format it will return AM and PM if you set
* false
*/
custom.set24HourFormat(false);
/**
* Pass Directly current data and time to show when ita pop up
*/
custom.setDate(Calendar.getInstance());
}
catch (Exception ex){
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Calendar Initialization Failed...", Toast.LENGTH_LONG).show();
}
findViewById(R.id.button_date).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
custom.showDialog();
}
});
}
public void getValues(){
var_Reminder_Title = et_Reminder_Title.getText().toString();
var_Reminder_Time = txt_Time.getText().toString();
var_Reminder_Date = txt_Date.getText().toString();
var_Reminder_Day = txt_Day.getText().toString();
var_Reminder_Description = et_Reminder_Description.getText().toString();
}
public boolean validate()
{
boolean allValid = true;
if(et_Reminder_Title.getText().toString().trim().length() == 0)
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
et_Reminder_Title.setError("Please Enter a Reminder Title here");
}
});
}
if(txt_Time.getText() == "Time")
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
et_Reminder_Title.setError("Tap Here to Select a Due Date and Time");
}
});
}
return allValid;
}
public void addReminder(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS reminders(ReminderId INTEGER PRIMARY KEY AUTOINCREMENT, ReminderTitle Text,ReminderTime Text,ReminderDate Text,ReminderDay Text, ReminderDescription Text);");
db.execSQL("INSERT INTO reminders(ReminderTitle,ReminderTime,ReminderDate,ReminderDay,ReminderDescription) VALUES('"+var_Reminder_Title+"','"+var_Reminder_Time+"','"+var_Reminder_Date+"','"+var_Reminder_Day+"','"+var_Reminder_Description+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Reminder Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Reminder Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void addNotification(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS notifications(NotificationId INTEGER PRIMARY KEY AUTOINCREMENT, NotificationTitle Text);");
db.execSQL("INSERT INTO notifications(NotificationTitle) VALUES('"+var_Reminder_Title+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Notification Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Notification Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void remind(){
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// set for 30 seconds later
alarmMgr.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + 30000, alarmIntent);
Toast.makeText(AddReminder.this, "Set Alarm", Toast.LENGTH_LONG).show();
}
public void al(){
// for Alarm 25/12/2012 at 12.00
Calendar myAlarmDate = Calendar.getInstance();
myAlarmDate.setTimeInMillis(System.currentTimeMillis());
myAlarmDate.set(var_Not_Year, var_Not_Month, var_Not_Day, var_Not_Hour, var_Not_Min, 0);
//Toast.makeText(AddReminder.this, ""+var_Not_Year+" "+ var_Not_Month+" "+ var_Not_Day+" "+var_Not_Hour+" "+var_Not_Min+" "+ 0, Toast.LENGTH_LONG).show();
//Create alarm manager
AlarmManager alarmMgr0 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Create pending intent & register it to your alarm notifier class
Intent intent0 = new Intent(this, AlarmReceiver.class);
//intent0.putExtra("Ringtone",getResources().getResourceName(R.raw.bbm_tone));
intent0.putExtra("Heading",var_Reminder_Title);
PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, intent0, 0);
//set timer you want alarm to work (here I have set it to 7.20pm)
//Intent intent0 = new Intent(this, OldEntryRemover.class);
/* Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.MONTH,12);
timeOff9.set(Calendar.DAY_OF_MONTH,1);
timeOff9.set(Calendar.YEAR,2015);
timeOff9.set(Calendar.HOUR_OF_DAY, 16);
timeOff9.set(Calendar.MINUTE, 45);
timeOff9.set(Calendar.SECOND, 0);
*/
//set that timer as a RTC Wakeup to alarm manager object
alarmMgr0.set(AlarmManager.RTC_WAKEUP, myAlarmDate.getTimeInMillis(), pendingIntent0);
// Toast.makeText(AddReminder.this, "Alarm", Toast.LENGTH_LONG).show();
}
#Override
public void onBackPressed ()
{
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.txtEditTime || v.getId() == R.id.txtEditDate || v.getId() == R.id.txtEditDay){
// custom.showDialog();
}
else if(v.getId() == R.id.imgBtnSubmitReminder) {
if (validate() == true) {
getValues();
addReminder();
// addNotification();
al();
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
}
}
}
this is custom date time picker class which is having the method showDialogue and it is using in the previous class. It is working perfectly on the version is less than 5.0 API but it is crashing on the version of 5.1 error is datetimepicker cannot be initialized.
public class CustomDateTimePicker implements android.view.View.OnClickListener {
private DatePicker datePicker;
private TimePicker timePicker;
private ViewSwitcher viewSwitcher;
private final int SET_DATE = 100, SET_TIME = 101, SET = 102, CANCEL = 103;
private Button btn_setDate, btn_setTime, btn_set, btn_cancel;
private Calendar calendar_date = null;
private Activity activity;
private ICustomDateTimeListener iCustomDateTimeListener = null;
private Dialog dialog;
private boolean is24HourView = true, isAutoDismiss = true;
private int selectedHour, selectedMinute;
public CustomDateTimePicker(Activity a,
ICustomDateTimeListener customDateTimeListener) {
activity = a;
iCustomDateTimeListener = customDateTimeListener;
dialog = new Dialog(activity);
// Context context = new ContextThemeWrapper(new MyContextWrapper, android.R.style.Theme_Holo_Light_Dialog);
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});
/*
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});*/
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View dialogView = getDateTimePickerLayout();
dialog.setContentView(dialogView);
}
public View getDateTimePickerLayout() {
LinearLayout.LayoutParams linear_match_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout.LayoutParams linear_wrap_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams frame_match_wrap = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
LinearLayout linear_main = new LinearLayout(activity);
linear_main.setLayoutParams(linear_match_wrap);
linear_main.setOrientation(LinearLayout.VERTICAL);
linear_main.setGravity(Gravity.CENTER);
LinearLayout linear_child = new LinearLayout(activity);
linear_child.setLayoutParams(linear_wrap_wrap);
linear_child.setOrientation(LinearLayout.VERTICAL);
LinearLayout linear_top = new LinearLayout(activity);
linear_top.setLayoutParams(linear_match_wrap);
btn_setDate = new Button(activity);
btn_setDate.setLayoutParams(button_params);
btn_setDate.setText("Set Date");
btn_setDate.setId(SET_DATE);
btn_setDate.setOnClickListener(this);
btn_setTime = new Button(activity);
btn_setTime.setLayoutParams(button_params);
btn_setTime.setText("Set Time");
btn_setTime.setId(SET_TIME);
btn_setTime.setOnClickListener(this);
linear_top.addView(btn_setDate);
linear_top.addView(btn_setTime);
viewSwitcher = new ViewSwitcher(activity);
viewSwitcher.setLayoutParams(frame_match_wrap);
datePicker = new DatePicker(activity);
timePicker = new TimePicker(activity);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
selectedHour = hourOfDay;
selectedMinute = minute;
}
});
viewSwitcher.addView(timePicker);
viewSwitcher.addView(datePicker);
LinearLayout linear_bottom = new LinearLayout(activity);
linear_match_wrap.topMargin = 8;
linear_bottom.setLayoutParams(linear_match_wrap);
btn_set = new Button(activity);
btn_set.setLayoutParams(button_params);
btn_set.setText("Set");
btn_set.setId(SET);
btn_set.setOnClickListener(this);
btn_cancel = new Button(activity);
btn_cancel.setLayoutParams(button_params);
btn_cancel.setText("Cancel");
btn_cancel.setId(CANCEL);
btn_cancel.setOnClickListener(this);
linear_bottom.addView(btn_set);
linear_bottom.addView(btn_cancel);
linear_child.addView(linear_top);
linear_child.addView(viewSwitcher);
linear_child.addView(linear_bottom);
linear_main.addView(linear_child);
//Invisible Calender View
datePicker.getCalendarView().setVisibility(View.GONE);
return linear_main;
}
public void showDialog() {
if (!dialog.isShowing()) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
selectedHour = calendar_date.get(Calendar.HOUR_OF_DAY);
selectedMinute = calendar_date.get(Calendar.MINUTE);
timePicker.setIs24HourView(is24HourView);
timePicker.setCurrentHour(selectedHour);
timePicker.setCurrentMinute(selectedMinute);
datePicker.updateDate(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DATE));
dialog.show();
btn_setDate.performClick();
btn_setTime.performClick();
}
}
public void setAutoDismiss(boolean isAutoDismiss) {
this.isAutoDismiss = isAutoDismiss;
}
public void dismissDialog() {
if (!dialog.isShowing())
dialog.dismiss();
}
public void setDate(Calendar calendar) {
if (calendar != null)
calendar_date = calendar;
}
public void setDate(Date date) {
if (date != null) {
calendar_date = Calendar.getInstance();
calendar_date.setTime(date);
}
}
public void setDate(int year, int month, int day) {
if (month < 12 && month >= 0 && day < 32 && day >= 0 && year > 100
&& year < 3000) {
calendar_date = Calendar.getInstance();
calendar_date.set(year, month, day);
}
}
public void setTimeIn24HourFormat(int hourIn24Format, int minute) {
if (hourIn24Format < 24 && hourIn24Format >= 0 && minute >= 0
&& minute < 60) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = true;
}
}
public void setTimeIn12HourFormat(int hourIn12Format, int minute,
boolean isAM) {
if (hourIn12Format < 13 && hourIn12Format > 0 && minute >= 0
&& minute < 60) {
if (hourIn12Format == 12)
hourIn12Format = 0;
int hourIn24Format = hourIn12Format;
if (!isAM)
hourIn24Format += 12;
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = false;
}
}
public void set24HourFormat(boolean is24HourFormat) {
is24HourView = is24HourFormat;
}
public interface ICustomDateTimeListener {
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName, int hour24,
int hour12, int min, int sec, String AM_PM);
public void onCancel();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case SET_DATE:
btn_setTime.setEnabled(true);
btn_setDate.setEnabled(false);
viewSwitcher.showNext();
break;
case SET_TIME:
btn_setTime.setEnabled(false);
btn_setDate.setEnabled(true);
viewSwitcher.showPrevious();
break;
case SET:
if (iCustomDateTimeListener != null) {
int month = datePicker.getMonth();
int year = datePicker.getYear();
int day = datePicker.getDayOfMonth();
calendar_date.set(year, month, day, selectedHour,
selectedMinute);
iCustomDateTimeListener.onSet(dialog, calendar_date,
calendar_date.getTime(), calendar_date
.get(Calendar.YEAR),
getMonthFullName(calendar_date.get(Calendar.MONTH)),
getMonthShortName(calendar_date.get(Calendar.MONTH)),
calendar_date.get(Calendar.MONTH), calendar_date
.get(Calendar.DAY_OF_MONTH),
getWeekDayFullName(calendar_date
.get(Calendar.DAY_OF_WEEK)),
getWeekDayShortName(calendar_date
.get(Calendar.DAY_OF_WEEK)), calendar_date
.get(Calendar.HOUR_OF_DAY),
getHourIn12Format(calendar_date
.get(Calendar.HOUR_OF_DAY)), calendar_date
.get(Calendar.MINUTE), calendar_date
.get(Calendar.SECOND), getAMPM(calendar_date));
}
if (dialog.isShowing() && isAutoDismiss)
dialog.dismiss();
break;
case CANCEL:
if (iCustomDateTimeListener != null)
iCustomDateTimeListener.onCancel();
if (dialog.isShowing())
dialog.dismiss();
break;
}
}
/**
* #param date
* date in String
* #param fromFormat
* format of your <b>date</b> eg: if your date is 2011-07-07
* 09:09:09 then your format will be <b>yyyy-MM-dd hh:mm:ss</b>
* #param toFormat
* format to which you want to convert your <b>date</b> eg: if
* required format is 31 July 2011 then the toFormat should be
* <b>d MMMM yyyy</b>
* #return formatted date
*/
public static String convertDate(String date, String fromFormat,
String toFormat) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
Date d = simpleDateFormat.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
simpleDateFormat = new SimpleDateFormat(toFormat);
simpleDateFormat.setCalendar(calendar);
date = simpleDateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
private String getMonthFullName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getMonthShortName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getWeekDayFullName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private String getWeekDayShortName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private int getHourIn12Format(int hour24) {
int hourIn12Format = 0;
if (hour24 == 0)
hourIn12Format = 12;
else if (hour24 <= 12)
hourIn12Format = hour24;
else
hourIn12Format = hour24 - 12;
return hourIn12Format;
}
private String getAMPM(Calendar calendar) {
String ampm = (calendar.get(Calendar.AM_PM) == (Calendar.AM)) ? "AM"
: "PM";
return ampm;
}
enter image description here
private void resetData() {
calendar_date = null;
is24HourView = true;
}
public static String pad(int integerToPad) {
if (integerToPad >= 10 || integerToPad < 0)
return String.valueOf(integerToPad);
else
return "0" + String.valueOf(integerToPad);
}
}
I am doing datepicker. I am facing some challenges. I am checking wheather selected date is weekend or not. If it is weekend then it should give current date only. Now I don't know where should I put condition in this program and how to get the day of the week and against which thing I should check.
Please, help me.
// TimePickerDialog.OnTimeSetListener
{
//Declaration for class
ButtonViews views;
dpListener dpListenerView;
// Declartion for member vairables
int day, month, x_year;
int hour;
int minute;
Calendar calendar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
views = new ButtonViews();
dpListenerView = new dpListener();
//ButtonListener
views.button_date.setOnClickListener(this);
views.button_time.setOnClickListener(this);
//
// pick up the default date using Calender class
calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
curr_date();
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
setupDate(day, month, x_year);
setupTime(hour, minute);
}
public void curr_date(){
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
x_year = calendar.get(Calendar.YEAR);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_date:
showDatePickerDialog();
break;
case R.id.button_time:
/* showTimePickerDialog();*/
break;
}
}
private void setupTime(int hours, int minutes) {
views.button_time.setText(hours + ":" + minutes);
}
private void setupDate(int day, int month, int year) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
String strMonth = ((month + 1) <= 9) ? ("0" + (month + 1)) : String.valueOf(month + 1);
views.button_date.setText(String.valueOf(day) + "/" + strMonth + "/" + String.valueOf(year));
String strDate = String.valueOf(day) + "/" + strMonth + "/" + String.valueOf(year);
Date d = null;
try {
d = (Date) sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
calendar.setTime(d);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek == 7 || dayOfWeek == 1) {
Toast.makeText(DateTimePickerActivity.this,"You have chosen weekend",Toast.LENGTH_SHORT);
}
}
private void showDatePickerDialog() {
DatePickerDialog datepickerdialog = new DatePickerDialog
(
this,
dpListenerView,
/* new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
} },*/
//this,
x_year,
month,
day
);
datepickerdialog.show();
}
class ButtonViews {
Button button_time;
Button button_date;
public ButtonViews() {
button_date = (Button) findViewById(R.id.button_date);
button_time = (Button) findViewById(R.id.button_time);
}
}
class dpListener implements OnDateSetListener {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
setupDate(dayOfMonth, monthOfYear, year);
/* if(dayOfWeek == 7 || dayOfWeek == 1) {*/
// as your requirement: you should display message they can not select the weekend" here
// then you set the value in datepickerdialog by current date
// Toast.makeText(DateTimePickerActivity.this
// , "You have selected weekend ", Toast.LENGTH_SHORT).show();
// }
}
}
}
i want to take the date that looks like that ("Year-mm-DD") from date picker in android studio and compare if it with the current date when i press a button.
public class UserMenu extends ActionBarActivity {
DatePicker date;
ImageButton next;
Date currentDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_menu);
date = (DatePicker) findViewById(R.id.datePicker);
next = (ImageButton) findViewById(R.id.nxt);
currentDate = new Date();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
String dateFormat = dateformat.format(new Date(date.getYear(), date.getMonth(), date.getDayOfMonth()));
String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(currentDate);
if (dateFormat.compareTo(nowDate) < 0) {
Toast.makeText(getApplicationContext(), "The date is too old", Toast.LENGTH_LONG);
} else {
Intent i = new Intent(UserMenu.this, UserMenuTime.class);
i.putExtra("date", dateFormat);
startActivity(i);
}
}
});
}
}
Use before and after methods to compare dates:
Date pickerDate = new Date(date.getYear(), date.getMonth(), date.getDayOfMonth());
if (pickerDate.before(currentDate)) {
Toast.makeText(getApplicationContext(), "The date is too old", Toast.LENGTH_LONG);
} else {
Intent i = new Intent(UserMenu.this, UserMenuTime.class);
i.putExtra("date", dateFormat);
startActivity(i);
}
I have this code which simply displays a countdown clock to an event. I am having an issue with it with regards to the last seconds place jumping digits unlike a normal clock. Here is the code I am working with. Could someone please offer some guidance to where this issue may be. Kind regards.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Timer().schedule(new TimerTask() {
File sdcard = Environment.getExternalStorageDirectory();
File cfgFile = new File(sdcard, "TimeTillParis/config.txt");
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
try {
InputStream is = new FileInputStream(cfgFile);
Properties prop = new Properties();
prop.load(is);
int mmY = Integer.parseInt(prop.getProperty("YEAR"));
int mmM = Integer.parseInt(prop.getProperty("MONTH"));
int mmD = Integer.parseInt(prop.getProperty("DAY"));
int mmH = Integer.parseInt(prop.getProperty("HOUR"));
int mmC = Integer.parseInt(prop.getProperty("MINUTE"));
int mmS = Integer.parseInt(prop.getProperty("SECOND"));
Calendar cal = Calendar.getInstance();
Date today = new Date(System.currentTimeMillis());
cal.set(Calendar.YEAR, mmY);
cal.set(Calendar.MONTH, mmM);
cal.set(Calendar.DAY_OF_MONTH, mmD);
cal.set(Calendar.HOUR_OF_DAY, mmH);
cal.set(Calendar.MINUTE, mmC);
cal.set(Calendar.SECOND, mmS);
long milliseconds = (cal.getTimeInMillis() - today.getTime());
String mD="", mH="", mM="", mS="", boxText="";
mD += (milliseconds / (1000*60*60*24));
mH += (milliseconds / (1000*60*60) % 24);
mM += (milliseconds / (1000*60) % 60);
mS += (milliseconds / 1000 % 60);
boxText += "Next visit to Paris in \n\n" +
mD + "d " +
mH + "h " +
mM + "m " +
mS + "s";
TextView textView = (TextView) findViewById(R.id.textView_date_display);
textView.setText(boxText);
} catch (FileNotFoundException e) {
String cfgNotFound="";
cfgNotFound += "config.txt not found!";
TextView textView = (TextView) findViewById(R.id.textView_date_display);
textView.setText(cfgNotFound);
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}, 0, 100);
}
}
I prepared complete solution, let me know if you have some questions:
public class MainActivity extends Activity {
private static final int COUNTDOWN_INTERVAL = 1000;
MyTimer timer;
Calendar eventTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File sdcard = Environment.getExternalStorageDirectory();
File cfgFile = new File(sdcard, "TimeTillParis/config.txt");
try {
InputStream is = new FileInputStream(cfgFile);
Properties prop = new Properties();
prop.load(is);
int mmY = Integer.parseInt(prop.getProperty("YEAR"));
int mmM = Integer.parseInt(prop.getProperty("MONTH"));
int mmD = Integer.parseInt(prop.getProperty("DAY"));
int mmH = Integer.parseInt(prop.getProperty("HOUR"));
int mmC = Integer.parseInt(prop.getProperty("MINUTE"));
int mmS = Integer.parseInt(prop.getProperty("SECOND"));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, mmY);
cal.set(Calendar.MONTH, mmM);
cal.set(Calendar.DAY_OF_MONTH, mmD);
cal.set(Calendar.HOUR_OF_DAY, mmH);
cal.set(Calendar.MINUTE, mmC);
cal.set(Calendar.SECOND, mmS);
eventTime = cal;
} catch (FileNotFoundException e) {
String cfgNotFound="";
cfgNotFound += "config.txt not found!";
TextView textView = (TextView) findViewById(R.id.textView_date_display);
textView.setText(cfgNotFound);
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
if(eventTime != null) {
long millisInFuture = (eventTime.getTimeInMillis() - System.currentTimeMillis());
timer = new MyTimer(this, millisInFuture, COUNTDOWN_INTERVAL);
timer.start();
}
}
#Override
protected void onPause() {
super.onPause();
if(timer != null) {
timer.cancel();
}
}
private static class MyTimer extends CountDownTimer {
TextView textView;
public MyTimer(Activity actitivy, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// findViewById is very expansive, so fined it only once
textView = (TextView) actitivy.findViewById(R.id.textView_date_display);
}
#Override
public void onFinish() {
}
#Override
public void onTick(long millisUntilFinished) {
SimpleDateFormat sdf = new SimpleDateFormat("'Next visit to Paris in \n\n'd'd 'h'h 'm'm 's's'");
String boxText = sdf.format(new Date(millisUntilFinished));
textView.setText(boxText);
}
}
}