Java TimePicker does not return right value - java

In android project I have this class
package mycalories.com.jalle.mycalories;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.widget.TimePicker;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
public static interface OnTimeSetListener {
void onTimeSet(Time time);
}
private OnTimeSetListener onTimeSetListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (onTimeSetListener != null) {
Time newTime =new Time(hourOfDay+":"+minute+ "");
onTimeSetListener.onTimeSet(newTime);
}
}
public void setOnTimeSetListener(OnTimeSetListener onTimeSetListener) {
this.onTimeSetListener = onTimeSetListener;
}
}
that should return Time selected. And in the main activity I have button and a text field:
Button btnTime = (Button) findViewById(R.id.btnTime);
btnTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TimePickerFragment timePicker = new TimePickerFragment();
timePicker.show(getFragmentManager(), "timePicker");
timePicker.setOnTimeSetListener(new OnTimeSetListener() {
#Override
public void onTimeSet(Time time) {
// SimpleDateFormat HHMM = new SimpleDateFormat("hh:mm");
final EditText txtTime = (EditText) findViewById(R.id.txtTime);
txtTime.setText(time.toString());
}
});
}
});
After selecting time I should have in format hh:mm but instead I got 19700101T00000011:55(4,0,0,0,0)
(obviously current time is not selected but default one)
I guess that the method onTimeSetis not right. Any idea ?
And one more q : How do I use same TimePicker class for multiple textboxes in diff activities ?

Time API has 3 constructors: no argument, String argument, and other Time argument. The constructor you are using, which is the String one, only accepts timezone as the expected value, and it will set the date to Jan 1, 1970.
public Time (String timezone)
Construct a Time object in the timezone named by
the string argument "timezone". The time is initialized to Jan 1,
1970.
If you want to return the Time with today's date and selected time, try changing the code to
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (onTimeSetListener != null) {
Time newTime = new Time();
newTime.setToNow();
newTime.hour = hourOfDay;
newTime.minute = minute;
onTimeSetListener.onTimeSet(newTime);
}
}

Knowing that you eventually want to display the time in hh:mm format, it would be easier to implement your interface method using the java.util.Date class, which SimpleDateFormat "plays nice" with. In the TimePickerFragment class, change the following:
public static interface OnTimeSetListener {
void onTimeSet(Date date);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (onTimeSetListener != null) {
Date date = new Date();
date.setHours(hourOfDay);
date.setMinutes(minute);
onTimeSetListener.onTimeSet(date);
}
}
And in the onClick() method:
public void onClick(View v)
{
TimePickerFragment timePicker = new TimePickerFragment();
timePicker.show(getFragmentManager(), "timePicker");
timePicker.setOnTimeSetListener(new TimePickerFragment.OnTimeSetListener() {
#Override
public void onTimeSet(Date date)
{
final EditText txtTime = (EditText) findViewById(R.id. txtTime);
SimpleDateFormat HHMM = new SimpleDateFormat("hh:mm");
txtTime.setText(HHMM.format(date));
}
}
);
}

Related

Setting up a start date and a end date to store into a firebase cloud?

Currently, I am creating a calendar app that will essentially have an employee choose a start date and an end date. The duration chosen between these dates will be the employees chosen holiday.
Now the problem is that I need to store 2 dates, which are the start date and the end date, into a firebase database. I intend to use this information later on so that I can compare the dates with other employees who may take the same week off (so validation will be needed). However, with my current code, I am only able to create a start date but not an end date, I am also unable to store information into the cloud, but I struggle to understand how I can retrieve the data in its current form.
For further clarification what I am trying to achieve is: I will have 2 buttons, startDateBtn and endDateBtn, both will initialize a calendar, the dates chosen will be stored/returned as strings and the data will be retrieved by a 3rd button called bookDatesBtn. This button will save the data into the cloud.
What I have tried:
Used a boolean variable set to false, if the startDateBtn is initialized the boolean variable is set to true, this will trigger an if-else statement and will set information for start date as a string. If the endDateBtn is initialized then the boolean variable will be set to false, this will keep information for the end date as a string.
DatePickerFragment.Java
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment{
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
}
}
HolidayScreen.Java
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Calendar;
public class HolidayScreen extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holiday_screen);
// //Setting listener for start date button for picking date
Button startButton = (Button) findViewById(R.id.startDateButton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "start date picker");
}
});
//Setting listener for start date button for picking date
Button endButton = (Button) findViewById(R.id.endDateButton);
endButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "end date picker");
}
});
//Setting listener for storing both dates into the cloud
Button bookButton = (Button) findViewById(R.id.bookButton);
bookButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This is where all the logic will go, so i will retrieve the start date information and then the-
//-end date information and store into firebase database
}
});
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView startTextView = (TextView) findViewById(R.id.startDateText);
startTextView.setText("Start Date: " + currentDateString);
}
}
The XML file will be provided on request.
This is my personal use code and it's working fine for my all device I think you should try this code...
I want to know which firebase database you have to use so after I can suggest it .. firebase real-time OR Cloud-firestore for store data...
for the whole code Visit My Code Link - https://github.com/axarlotwala/CafeDelear/blob/master/app/src/main/java/com/cafedelear/aksha/cafedelear/Fragment/ProductOfferFragment.java
/*method of start offer*/
private void offerStart() {
final Calendar calendar = Calendar.getInstance();
myear = calendar.get(Calendar.YEAR);
dmonth = calendar.get(Calendar.MONTH);
mdate = calendar.get(Calendar.DAY_OF_MONTH);
dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
start_date.setText(year + "-" + (month+1) + "-" + dayOfMonth);
}
},myear,dmonth,mdate);
dialog.show();
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
}
private void offerEnd(){
final Calendar calendar = Calendar.getInstance();
myear = calendar.get(Calendar.YEAR);
dmonth = calendar.get(Calendar.MONTH);
mdate = calendar.get(Calendar.DAY_OF_MONTH);
calendar.roll(Calendar.DATE,1);
dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
end_date.setText(year + "-" + (month+1) + "-" + dayOfMonth);
}
},myear,dmonth,mdate);
dialog.show();
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
//if offer end date is selected is also start Offer date then offer end time is Date-23-59-59
}
here is you can understand for previous or new date in your textview first set then use it
previous date:
public void previousDate(Context context, TextView textView) {
mCalendarAlarm = Calendar.getInstance();
mCalendarAlarm.setTimeZone(TimeZone.getDefault());
DatePickerDialog datePickerDialog =
new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> {
mCalendarAlarm.set(Calendar.YEAR, year);
mCalendarAlarm.set(Calendar.MONTH, monthOfYear);
mCalendarAlarm.set(Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String datetime = dateFormat.format(mCalendarAlarm.getTime());
textView.setText(datetime);
}, mCalendarAlarm.get(Calendar.YEAR), mCalendarAlarm.get(Calendar.MONTH),
mCalendarAlarm.get(Calendar.DAY_OF_MONTH));
datePickerDialog.getDatePicker().
setMaxDate(mCalendarAlarm.getTimeInMillis());
datePickerDialog.show();
}
for next date:
public void NextDate(Context context, TextView textView) {
mCalendarAlarm = Calendar.getInstance();
mCalendarAlarm.setTimeZone(TimeZone.getDefault());
DatePickerDialog datePickerDialog =
new DatePickerDialog(context, (view, year, monthOfYear, dayOfMonth) -> {
mCalendarAlarm.set(Calendar.YEAR, year);
mCalendarAlarm.set(Calendar.MONTH, monthOfYear);
mCalendarAlarm.set(Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String datetime = dateFormat.format(mCalendarAlarm.getTime());
textView.setText(datetime);
}, mCalendarAlarm.get(Calendar.YEAR), mCalendarAlarm.get(Calendar.MONTH),
mCalendarAlarm.get(Calendar.DAY_OF_MONTH));
datePickerDialog.getDatePicker().
setMinDate(mCalendarAlarm.getTimeInMillis());
datePickerDialog.show();
}

Time Picker is not working when i set time 12:00 or 00:00 its displaying AM instead Pm

when i select 12:00 or i Select 0:00 it showing me only AM not PM tried a lot but not getting the required output and I search same question in stack overflow but not getting the output..
Here the complete code is as follow:-
main.java
package com.Weal.sachin.omcom;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import java.util.Calendar;
import java.util.Locale;
import android.view.ViewGroup;
import android.widget.EditText;
import android.app.TimePickerDialog;
import android.widget.TimePicker;
public class Daily_Task extends Fragment {
public Daily_Task(){};
boolean isFromClicked = false;
boolean morning = true;
private int hour;
private int minute;
String addtask, adddetail, addstart, addend;
static final int TIME_DIALOG_ID = 999;
View view;
EditText starttime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_daily__task, container, false);
getActivity().setTitle("Task");
starttime = (EditText) view.findViewById(R.id.start_time);
setCurrentTimeOnView();
addListenerOnButton();
return view;
}
// display current time
public void setCurrentTimeOnView() {
// starttime= (EditText)view.findViewById(R.id.start_time);
// timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR);
minute = c.get(Calendar.MINUTE);
// set current time into textview
starttime.setText(getTimeText(hour, minute));
// set current time into timepicker
//timePicker1.setCurrentHour(hour);
//timePicker1.setCurrentMinute(minute);
}
public void addListenerOnButton() {
// starttime = (EditText) view.findViewById(R.id.start_time);
starttime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
isFromClicked = false;
}
});
}
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
// set current time into textview
if (isFromClicked)
starttime.setText(getTimeText(hour, minute));
else{
}
//btnChangeTime.setText(getTimeText(hour, minute));
// set current time into timepicker
// timePicker1.setCurrentHour(hour);
// timePicker1.setCurrentMinute(minute);
}
};
private void showTimePickerDialog() {
new TimePickerDialog(getContext(), timePickerListener, hour, minute, true).show();
}
private String getTimeText(int hourOfDay, int minute) {
int hour = hourOfDay % 12;
if (hour == 0) hour = 12 ;
//then
if (hour >=12 && hour < 24) morning = false;
else morning = true;
String _AM_PM = (hourOfDay > 12) ? "PM" : "AM";
return String.format(Locale.getDefault(), "%02d:%02d %s", hour, minute, _AM_PM);
}
}
I Tried this code and now it is working perfectly for me:-
TimePicker.java
package com.Weal.sachin.omcom;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
import java.util.Date;
/**
* Created by sachin on 2/2/2017.
*/
public class TImePickerEndTime extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
// Get a Calendar instance
final Calendar calendar = Calendar.getInstance();
// Get the current hour and minute
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
// TimePickerDialog Theme : THEME_DEVICE_DEFAULT_LIGHT
TimePickerDialog tpd = new TimePickerDialog(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT,this,hour,minute,false);
// TimePickerDialog Theme : THEME_DEVICE_DEFAULT_DARK
TimePickerDialog tpd2 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_DARK,this,hour,minute,false);
// TimePickerDialog Theme : THEME_HOLO_DARK
TimePickerDialog tpd3 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_DARK,this,hour,minute,false);
// TimePickerDialog Theme : THEME_HOLO_LIGHT
TimePickerDialog tpd4 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT,this,hour,minute,false);
// TimePickerDialog Theme : THEME_TRADITIONAL
TimePickerDialog tpd5 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_TRADITIONAL,this,hour,minute,false);
// Return the TimePickerDialog
return tpd;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
String am_pm = "";
String tm = new SimpleDateFormat("HH:mm").format(new Date(hourOfDay));
Calendar datetime1 = Calendar.getInstance();
datetime1.set(Calendar.HOUR_OF_DAY, hourOfDay);
datetime1.set(Calendar.MINUTE, minute);
String strDate = tm.format(String.valueOf(datetime1.getTime()));
if (datetime1.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime1.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
String strHrsToShow1 = (datetime1.get(Calendar.HOUR) == 00)?"12":datetime1.get(Calendar.HOUR)+"";
// ((EditText)getActivity().findViewById(R.id.End_time)).setText(String.format("%02d:%02d", strHrsToShow1, datetime1.get(Calendar.MINUTE) + "") +" "+am_pm);
// ((EditText)getActivity().findViewById(R.id.End_time)).setText(String.format("%02d:%02d", strHrsToShow1, datetime1.get(Calendar.MINUTE)));
/*((EditText)getActivity().findViewById(R.id.End_time)
).setText( String.format("%02d:%02d", strHrsToShow1, datetime1.get(Calendar.MINUTE) + "") +" "+am_pm);
*/
int hour = hourOfDay % 12;
((EditText) getActivity().findViewById(R.id.End_time)).setText(String.format("%02d:%02d %s", hour == 0 ? 12 : hour,
minute, hourOfDay < 12 ? "am" : "pm"));
}
}
now in Main.java
//
timepicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Initialize a new time picker dialog fragment
DialogFragment dFragment1 = new TImePicker();
// Show the time picker dialog fragment
dFragment1.show(getActivity().getFragmentManager(),"Time Picker");
}
});

Error coverting Integer variables to Date Object and value returned is always 31-DEC - 1?

I have written this line of code of code:
dateSelected = new GregorianCalendar(tempYear, tempMonth, tempDate,tempHour,tempMinute).getTime();
I got these value from datepicker and timepicker dialogs in android. I am able to get correct values in these integer variables but when I convert them to Date object it will always be 31 dec. I am not able to fix the problem.
I have also tried this approach as well:
Calendar calendar = Calendar.getInstance();
calendar.set(tempYear, tempMonth, tempDate, tempHour, tempMinute);
dateSelected = calendar.getTime();
Whenever Second line is commented out it is working fine. I am perfectly getting current date and time. But when it is uncommented the problem returns.
In case anyone needs my full code:
package com.bignerdranch.android.todolistwithdate;
/**********************************************
* This activity will open new dialog box that will add new
* ToDo list item to the list.
*/
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class AddToDoActivity extends AppCompatActivity {
EditText entryName;
Button dateSelectionButton;
Button addEntry;
Date dateSelected;
Button timeSelectionButton;
private int tempDate, tempMonth, tempYear, tempHour, tempMinute;
String nameToDoItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_do);
entryName = (EditText)findViewById(R.id.new_todo_edittext);
dateSelectionButton = (Button)findViewById(R.id.date_selection_button);
addEntry = (Button)findViewById(R.id.entry_add_button);
timeSelectionButton = (Button)findViewById(R.id.time_selection_button);
//Create date selection Dialog here
//Also add code for modifying dateSelected Variable
dateSelectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePickerDialog = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
super.onDateSet(view, year, monthOfYear, dayOfMonth);
dateSelectionButton.setText(Integer.toString(dayOfMonth) + "/" + Integer.toString(monthOfYear + 1) + "/" + Integer.toString(year));
tempDate = dayOfMonth;
tempMonth = monthOfYear;
tempYear = year;
}
};
datePickerDialog.show(getSupportFragmentManager(), "datePicker");
}
});
timeSelectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePickerDialog = new TimePickerFragment() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
super.onTimeSet(view, hourOfDay, minute);
timeSelectionButton.setText(Integer.toString(hourOfDay) + ":" + Integer.toString(minute));
tempHour = hourOfDay;
tempMinute = minute;
}
};
timePickerDialog.show(getSupportFragmentManager(), "timePicker");
}
});
//Work here to get calendar working properly
Calendar calendar = Calendar.getInstance();
calendar.set(tempYear, tempMonth, tempDate, tempHour, tempMinute);
dateSelected = calendar.getTime();
entryName = (EditText)findViewById(R.id.new_todo_edittext);
addEntry = (Button)findViewById(R.id.entry_add_button);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameToDoItem = entryName.getText().toString();
Intent resultIntent = new Intent();
resultIntent.putExtra("NameOfItem", nameToDoItem);
resultIntent.putExtra("DateOfItem", dateSelected);
setResult(Activity.RESULT_OK, resultIntent);
Log.i("Date: ", dateSelected.toString() );
finish();
}
});
}
}
When the code works all variables equal to 0 because a user doesn't pick a date and a time at the moment.
Calendar calendar = Calendar.getInstance();
calendar.set(tempYear, tempMonth, tempDate, tempHour, tempMinute);
dateSelected = calendar.getTime();
Move the code in addEntry's onClickListener implementation and it will work 👍

Android: How to implement an ArrayList with holidays dates

I'm developing application that in one of its activity has the mechanism that calculates workdays between two dates:
package com.example.salary;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
public class CountingWorkDays extends Activity {
static Calendar start_calendar = Calendar.getInstance();
static Calendar end_calendar = Calendar.getInstance();
EditText et_start;
EditText et_end;
Button count;
Button save_days;
static int workDays = 0;
static int totalDays = 0;
int dni_robocze = 0;
Calendar start_calendar_save = Calendar.getInstance();
Calendar end_calendar_save = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.przeliczanie_dni_roboczych);
gather_start_date();
gather_end_date();
after_clicking_count();
after_clicking_save();
}
private void update_et(EditText edittext, Calendar myCalendar) { //inserting to EditText object
String myFormat = "dd/MM/yy";
SimpleDateFormat date = new SimpleDateFormat(myFormat, Locale.UK);
edittext.setText(date.format(myCalendar.getTime()));
}
public void gather_start_date() { //getting start date
et_start = (EditText) findViewById(R.id.et_od);
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
start_calendar.set(Calendar.YEAR, year);
start_calendar.set(Calendar.MONTH, monthOfYear);
start_calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
update_et(et_start, start_calendar);
}
};
et_start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(PrzeliczanieDniRoboczych.this, date,
start_calendar.get(Calendar.YEAR), start_calendar
.get(Calendar.MONTH), start_calendar
.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
public void gather_end_date() { //getting end date
et_end = (EditText) findViewById(R.id.et_do);
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
end_calendar.set(Calendar.YEAR, year);
end_calendar.set(Calendar.MONTH, monthOfYear);
end_calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
update_et(et_end, end_calendar);
}
};
et_end.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(PrzeliczanieDniRoboczych.this, date,
end_calendar.get(Calendar.YEAR), end_calendar
.get(Calendar.MONTH), end_calendar
.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
public void after_clicking_count() { //after clicking "Calculate"
work_days = 0;
count = (Button) findViewById(R.id.b_count_workdays);
count.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
work_days = getWorkingDaysBetweenTwoDates();
}
});
}
public int getWorkingDaysBetweenTwoDates() { //getting working days between two dates
workDays = 0;
totalDays = 0;
// Return 0 if start and end are the same
if (et_start.getText().toString().trim().length() == 0
|| et_end.getText().toString().trim().length() == 0
|| et_start.getText().toString().matches("dd/mm/yy")
|| et_end.getText().toString().matches("dd/mm/yy")) {
Toast.makeText(getApplicationContext(), "Choose dates!",
Toast.LENGTH_SHORT).show();
return 0;
} else {
if (start_calendar.getTimeInMillis() > end_calendar
.getTimeInMillis()) {
Toast.makeText(PrzeliczanieDniRoboczych.this,
"Start date has to be before end date",
Toast.LENGTH_SHORT).show();
} else {
for (; start_calendar.getTimeInMillis() <= end_calendar
.getTimeInMillis(); start_calendar.add(
Calendar.DAY_OF_MONTH, 1)) {
totalDays++;
if (start_calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
&& start_calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
workDays++;
}
}
start_calendar.add(Calendar.DAY_OF_MONTH, -1 * totalDays);
Toast.makeText(PrzeliczanieDniRoboczych.this,
"Workday is this period are: " + workDays,
Toast.LENGTH_SHORT).show();
}
return workDays;
}
}
I would like to add the mechanism that will allow user to insert dates of holidays (this aplication will calculate the salary and holidays means no salary, so it's important).
As I saw here, user SimplyPanda suggested adding an ArrayList<Integer> to do so. However, I wondering how the inserting by user should look like.
Should user know the integer representation of particular dates in Java? - I guess no.
Does anyone have any idea how to implement such functionality?

Completing UI Activity assignment [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a UI Lab for Android Programming that I'm trying to complete. I think I'm close, yet so far away. I have four activities that I'm working with but only three of them needed worked on. Here is what I have. I need help with what I'm missing.
Here's the first Activity which is AddToDoActivity
package course.labs.todomanager;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import course.labs.todomanager.ToDoItem.Priority;
import course.labs.todomanager.ToDoItem.Status;
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()");
//TODO - Implement onClick().
Intent intent = new Intent setResult;
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()");
//TODO - Reset data fields to default values
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
//TODO - Get Priority
Priority priority = getPriority();
//TODO - Get Status
Status status = getStatus();
//TODO - Title
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);
//TODO - return data Intent and finish
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.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
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 year, int monthOfYear, int dayOfMonth) {
// 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 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 view, int year, int monthOfYear,
int dayOfMonth) {
setDateString(year, monthOfYear, dayOfMonth);
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 second activity which is ToDoItem
package course.labs.todomanager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Intent;
// Do not modify
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(
"yyyy-MM-dd 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);
}
}
Here's the third activity which is ToDoListAdapter
package course.labs.todomanager;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import course.labs.todomanager.ToDoItem.Status;
public class ToDoListAdapter extends BaseAdapter {
// List of ToDoItems
private final List<ToDoItem> mItems = new ArrayList<ToDoItem>();
private final Context mContext;
private static final String TAG = "Lab-UserInterface";
public ToDoListAdapter(Context context) {
mContext = context;
}
// Add a ToDoItem to the adapter
// Notify observers that the data set has changed
public void add(ToDoItem item) {
mItems.add(item);
notifyDataSetChanged();
}
// Clears the list adapter of all items.
public void clear(){
mItems.clear();
notifyDataSetChanged();
}
// Returns the number of ToDoItems
#Override
public int getCount() {
return mItems.size();
}
// Retrieve the number of ToDoItems
#Override
public Object getItem(int pos) {
return mItems.get(pos);
}
// Get the ID for the ToDoItem
// In this case it's just the position
#Override
public long getItemId(int pos) {
return pos;
}
//Create a View to display the ToDoItem
// at specified position in mItems
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//TODO - Get the current ToDoItem
final ToDoItem toDoItem = getItemPos();
//TODO - Inflate the View for this ToDoItem
// from todo_item.xml.
LayoutInflater = itemLayout;
RelativeLayout itemLayout = m.context.getSystemService(R.layout.todo_item);
//TODO - Fill in specific ToDoItem data
// Remember that the data that goes in this View
// corresponds to the user interface elements defined
// in the layout file
//TODO - Display Title in TextView
final TextView titleView = ItemLayout.findViewById;
setTextView;
//TODO - Set up Status CheckBox
final CheckBox statusView = ItemLayout.findViewById(R.id.statusCheckBox);
statusView.setChecked(checked) statusDone;
statusView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
log("Entered onCheckedChanged()");
//TODO - Set up and implement an OnCheckedChangeListener, which
// is called when the user toggles the status checkbox
if isChecked ToDoItem.setStatus status.Done(true);
else
}
});
//TODO - Display Priority in a TextView
final TextView priorityView = findViewByID(R.id.PriorityView);
PriorityView.setToString();
//TODO - Display Time and Date.
// Hint - use ToDoItem.FORMAT.format(toDoItem.getDate()) to get date and time String
final TextView dateView = itemLayout.findViewById(R.id.dateView);
dateView.setText(ToDoItem.FORMAT);
// Return the View you just created
return itemLayout;
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
And here is the fourth activity which is ToDoManagerActivity
package course.labs.todomanager;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Date;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import course.labs.todomanager.ToDoItem.Priority;
import course.labs.todomanager.ToDoItem.Status;
public class ToDoManagerActivity extends ListActivity {
// Add a ToDoItem Request Code
private static final int ADD_TODO_ITEM_REQUEST = 0;
private static final String FILE_NAME = "TodoManagerActivityData.txt";
private static final String TAG = "Lab-UserInterface";
// IDs for menu items
private static final int MENU_DELETE = Menu.FIRST;
private static final int MENU_DUMP = Menu.FIRST + 1;
ToDoListAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a new TodoListAdapter for this ListActivity's ListView
mAdapter = new ToDoListAdapter(getApplicationContext());
// Put divider between ToDoItems and FooterView
getListView().setFooterDividersEnabled(true);
//TODO - Inflate footerView for footer_view.xml file
TextView footerView = TextView().getLayoutInflater()
.inflate(R.layout.footer_view, null);
//TODO - Add footerView to ListView
getListView fv = (ListView)findViewById(R.layout.footer_view);
footerView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered footerView.OnClickListener.onClick()");
//TODO - Attach Listener to FooterView. Implement onClick().
Intent intent = new Intent(getBaseContext(), AddToDoActivity.class);
startActivityForResult(intent, ADD_TODO_ITEM_REQUEST);
}
});
//TODO - Attach the adapter to this ListActivity's ListView
getListView.footer_view.setAdapter(mAdapter, fv);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
log("Entered onActivityResult()");
// TODO - Check result code and request code.
// If user submitted a new ToDoItem
// Create a new ToDoItem from the data Intent
// and then add it to the adapter
if requestCode == ADD_TODO_ITEM_REQUEST {
also if resultCode != RESULT_OK(true);
new mAdapter++;
}
}
// Do not modify below here
#Override
public void onResume() {
super.onResume();
// Load saved ToDoItems, if necessary
if (mAdapter.getCount() == 0)
loadItems();
}
#Override
protected void onPause() {
super.onPause();
// Save ToDoItems
saveItems();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, "Delete all");
menu.add(Menu.NONE, MENU_DUMP, Menu.NONE, "Dump to log");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_DELETE:
mAdapter.clear();
return true;
case MENU_DUMP:
dump();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void dump() {
for (int i = 0; i < mAdapter.getCount(); i++) {
String data = ((ToDoItem) mAdapter.getItem(i)).toLog();
log("Item " + i + ": " + data.replace(ToDoItem.ITEM_SEP, ","));
}
}
// Load stored ToDoItems
private void loadItems() {
BufferedReader reader = null;
try {
FileInputStream fis = openFileInput(FILE_NAME);
reader = new BufferedReader(new InputStreamReader(fis));
String title = null;
String priority = null;
String status = null;
Date date = null;
while (null != (title = reader.readLine())) {
priority = reader.readLine();
status = reader.readLine();
date = ToDoItem.FORMAT.parse(reader.readLine());
mAdapter.add(new ToDoItem(title, Priority.valueOf(priority),
Status.valueOf(status), date));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Save ToDoItems to file
private void saveItems() {
PrintWriter writer = null;
try {
FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
fos)));
for (int idx = 0; idx < mAdapter.getCount(); idx++) {
writer.println(mAdapter.getItem(idx));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != writer) {
writer.close();
}
}
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
Any thought on how to improve the cancelButton code in the AddToDoAcitivity?
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
//TODO - Implement onClick().
Intent intent = new Intent setResult;
finish();
}
});
change your AddToDoActivity code like this
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);
}
}

Categories

Resources