Android - Java - Get Access to TimePickerDialog - java

Hi I currently have a TimePickerDialog:
TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet( TimePicker view, int hourOfDay, int minute ) {
c.set( Calendar.HOUR_OF_DAY, hourOfDay );
c.set( Calendar.MINUTE, minute );
String hour = Integer.toString(hourOfDay);
String min = Integer.toString(minute);
String timeStamp = hour + ":" + min;
}
};
However I just want to know how can I gain access to the TimeStamp String outside of the method ? As I need to use it again to send it into another method which inputs it into a JSON Object. I did try making the String Final or Public but just got errors.

Just make a field to the class named timeStamp and change it.
Example:
public class Outside
{
private String timeStamp;
TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet( TimePicker view, int hourOfDay, int minute ) {
c.set( Calendar.HOUR_OF_DAY, hourOfDay );
c.set( Calendar.MINUTE, minute );
String hour = Integer.toString(hourOfDay);
String min = Integer.toString(minute);
timeStamp = hour + ":" + min;
}
};
}
I removed String timeStamp "String" because you now refer to the field.
Now timeStamp will contains hour + ":" + min when onTimeSet is called.
P.S You cannot make it final since it will change everytime onTimeSet is called.

Related

period.getDays() return each time 0 in android

I try to get the correct difference time between the current day and second selected day from the calendar.
I'm using in this case LocalDate and the 3 methods getDays() getMonths() getYears() to get the day and the month also the year:
public int dateDiff(int year,int month,int day) {
final int Day = c.get(Calendar.DAY_OF_MONTH);
final int Month = c.get(Calendar.MONTH);
final int Year = c.get(Calendar.YEAR);
LocalDate localDate1 = LocalDate.of(year,month,day);
LocalDate localDate2 = LocalDate.of(Year,Month,Day);
Period period = Period.between(localDate2,localDate1);
int dayDiff = period.getDays();
return dayDiff;
}
public void onSelectedDayChange(#NonNull CalendarView view, final int year, final int month, final int dayOfMonth) {
textView.setText(""+dateDiff(year, month, day));
}
But each time when I test the code I got in the textView "0"
I try to see the value of the variable "period" and I got (P2M8D 'this result got in my example') that's mean the variable period count the difference between the days and the problem in the methods.
How can I solve this problem?
The problem in this project are in the name of variables, I'm using the same name of current time and the selected time I just change the first letter with capital one but this make problem.
That's why every time when i run the project i got 0
I change the program like that:
public int dateDiff(int year,int month,int day) {
final int dayOfToday = c.get(Calendar.DAY_OF_MONTH);
final int monthOfToday = c.get(Calendar.MONTH);
final int yearOfToday = c.get(Calendar.YEAR);
LocalDate localDate1 = LocalDate.of(year,month,day);
LocalDate localDate2 = LocalDate.of(Year,Month,Day);
Period period = Period.between(localDate2,localDate1);
int dayDiff = period.getDays();
return dayDiff;
}
Here, this should help.
public int dateDiff(int year,int month,int day) {
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,day);
thatDay.set(Calendar.MONTH,month); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, year);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
return days;
}

Get time from textview and show exact time in the timepickerdialog

Actually, I am frustrated because after so many tries I haven't got any success in getting time from the textview and show it in the TimePickerDialog.
Whenever I click on the layout to get the TimePickerDialog, it always shows 12:00 AM.
I want when I click on this and timepicker will show this time which is on the image.
Here is my code:
public void a(final TextView txv){
TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
datetime = Calendar.getInstance();
currentHour=datetime.get(Calendar.HOUR_OF_DAY);
currentMinute=datetime.get(Calendar.MINUTE);
int hour = hourOfDay % 12;
if (hour == 0)
hour = 12;
String strHrsToShow = (String.format("%02d:%02d %s", hour == 0 ? 12 : hour, minute, hourOfDay < 12 ? "AM" : "PM"));
finalTime = strHrsToShow;
if (txv.equals(wakeUpTime)) {
wakeUpTime.setText(finalTime);
}
editor.commit();
}
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
Initialise currentHour, currentMinute to avoid default 12:00 AM.
currentHour = 12;
currentMinute = 34;
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
... omitted...
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
After creating object for TimePickerDialog "thetimePickerDialog",
use:
timePickerDialog.update(int hourOfDay, int minuteOfHour);
Which in your case will be :
timePickerDialog.update(currentHour,currentMinute);

Displaying time elapsed since epoch

I am working on creating a time app that calculates both the current time and the time elapsed since midnight, January 1, 1970, in milliseconds. I went ahead and used Calendar and was able to successfully return the current time but for some reason the elapsed time returns 0. Not sure why that would be.
Here is my current code:
import java.util.Calendar;
import java.util.TimeZone;
public class TimeApp {
public static void main(String[] args) {
Time time1 = new Time();
System.out.println("Hour: " + time1.getHour() + " Minute: " +
time1.getMinute() + " Second: " + time1.getSecond());
Time time2 = new Time();
System.out.println("Elapsed time since epoch: " + time2.getElapsedTime());
}
}
final class Time {
private int hour;
private int minute;
private int second;
private long secondsSinceEpoch;
public Time() {
Calendar calendar = Calendar.getInstance();
this.second = calendar.get(Calendar.SECOND);
this.minute = calendar.get(Calendar.MINUTE);
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
}
public Time(long elapsedTime) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(2016, Calendar.SEPTEMBER, 9);
secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
}
#Override
public String toString() {
return hour + ":" + minute + ":" + second;
}
public int getHour() {
return hour;
}
public int getMinute() {
return minute;
}
public int getSecond() {
return second;
}
public long getElapsedTime() {
return secondsSinceEpoch;
}
}
You aren't setting elapsedTime for time2. I think you wanted
Time time2 = new Time(System.currentTimeMillis());
And as pointed out in the comments, you aren't using elapsedTime in your constructor. Something like
public Time(long elapsedTime) {
secondsSinceEpoch = elapsedTime / 1000;
}
I think you are using the wrong constructor for time2 since you called Time() and this version does not set secondsSinceEpoch. Try using your other constructor Time(long elapsedTime) with any long value and see if it works.
Like this ..
Time time2 = new Time(10000);
Then re-write this constructor since you never use elapsedTime anyway, or delete it completely and re-write the first constructor to assign a value to secondsSinceEpoch.
public Time() {
Calendar calendar = Calendar.getInstance();
this.second = calendar.get(Calendar.SECOND);
this.minute = calendar.get(Calendar.MINUTE);
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
}

how to get MONTHS, DAYS and weeks (android datepicker)

UPDATE
I am creating a pregnancy due date countdown, so I use android.widget.DatePicker as a tool to set the due date.
For example:
the set due date is Jan. 9 2015
the date now is Nov. 9 2014
so the left months, days and weeks is 2 months, 62 days and 8weeks
So far i can only display the set due date.
Question:
How to get the exact months weeks and days left when the user set the due date.
UPDATE CODE
Here's the code:
private TextView txtResultDueDate ;
private DatePicker datePicker;
private Calendar calendar;
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 999;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
txtResultDueDate = (TextView) findViewById(R.id.txtDue);
btnChangeDate = (Button)findViewById(R.id.button1);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
#SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
.show();
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
Chronology chrono = GregorianChronology.getInstance();
DateTime end = new DateTime(arg0.getYear(), arg0.getMonth(), arg0.getDayOfMonth(), 0, 0, chrono);
DateTime current = new DateTime();
Interval interval = new Interval(current.toInstant(), end.toInstant());
Period duePeriod = interval.toPeriod();
showDate(duePeriod.getYears(), duePeriod.getMonths(), duePeriod.getDays());
}
};
private void showDate(int year, int month, int day) {
txtResultDueDate.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
This is the error that I encounter when I set the due date using DatePicker:
FATAL EXCEPTION: main
java.lang.IllegalArgumentException: The end instant must be greater orequal to the start
at org.joda.time.base.Abstraction.checkInterval(AbstractInterval.java.63)
at org.joda.time.base.BaseInterval(BaseInterval.java:94)
at org.joda.time.Interval.(Interval.java.122)
at com.date.androin.Profile$1.onDataset(Profile.java:168)
at android.app.DatePickerDialog.tryNotifyDataSet(DatePickerDialog.java.148)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java.116)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStrat.main(Native Method)
There is a library Joda Time. It is better the Date API provided by Java
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
Yes, you can use joda lib with android DatePicker
Chronology chrono = GregorianChronology.getInstance();
// end datetime
DateTime end = new DateTime(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 0, 0 ,chrono);
// current datetime
DateTime current = new DateTime();
Then instantiate Interval with start and end datetime
Interval interval = new Interval(current.toInstant(), end.toInstant());
then use the Interval api to get the Period from which you can extract the difference of months/days/weeks
Period duePeriod = interval.toPeriod();
// get difference in months
duePeriod.getMonths();
// get difference in weeks
duePeriod.getWeeks();
PLease refer the below Javadoc of Period for complete list of API
http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html
For Android, in your case add the above code into your DatePicker onDateSet listener. finally the listener method would like this,
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
// TODO Auto-generated method stub
Chronology chrono = GregorianChronology.getInstance();
// end datetime
DateTime end = new DateTime(arg0.getYear(), arg0.getMonth(), arg0.getDayOfMonth(), 0, 0, chrono);
// current datetime
DateTime current = new DateTime();
Interval interval = new Interval(current.toInstant(), end.toInstant());
Period duePeriod = interval.toPeriod();
showDate(duePeriod.getYears(), duePeriod.getMonths(), duePeriod.getDays());
}
//somewhere in your code, init part
Calendar then = setDate(9, 0, 2015);//9 january 2015
Calendar c = Calendar.getInstance();
Calendar now = setDate(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
String leftDays = getLeftDays(then, now);//your result
//method setting days months years - we ignore hours and minutes
private String getLeftDays(Calendar then, Calendar now) {
long leftMilis = then.getTimeInMillis() - now.getTimeInMillis();
int seconds = (int) (leftMilis / 1000);
Log.d(TAG, "seconds:" + seconds);
int minutes = seconds / 60;
Log.d(TAG, "minutes:" + minutes);
int hours = minutes / 60;
Log.d(TAG, "hours:" + hours);
int days = hours / 24;
Log.d(TAG, "days:" + days);
int weeks = days / 7;
Log.d(TAG, "weeks:" + weeks);
//months.. another way calculating data due not equal amount of days per month
Calendar temp = ((Calendar) then.clone());
temp.add(Calendar.MONTH, -now.get(Calendar.MONTH));
int months = temp.get(Calendar.MONTH);
Log.d(TAG, "months:" + months);
StringBuilder sb = new StringBuilder();
String format = "%d months, %d days, %d weeks";
String formatStr = String.format(format, months, days, weeks);
String result = sb.append(formatStr).toString();
Log.d(TAG, sb.toString());
return result;
}
private Calendar setDate(int day, int month, int year) {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, day);
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Log.d(TAG, c.getTime().toString());
return c;
}
Calendar c = calendar.getInstance();
and DatePickerDialog d
#Override
public void onDateSet(DatePicker view,int Year,int mont of Year,int day of month){
Toast
c.get(Calendar.Year),c.get(Calendar.Month),c.get(Calendar.Day_of_Month);
d.show
this code is to find week from selected date,it's proper work.
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(Integer.parseInt(selected_year), Integer.parseInt(selected_month), Integer.parseInt(selected_date)); // set date 1 (yyyy,mm,dd)
System.out.println("Selected Date==>>" + date1);
date2.clear();
date2.set(Integer.parseInt(current_year), Integer.parseInt(current_month), Integer.parseInt(current_date));
System.out.println("Current Date==>>" + date2);
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
week = (int) (dayCount / 7);
if (week <= 0) {
Toast.makeText(this, "Sry System Error", Toast.LENGTH_SHORT).show();
System.out.println("Week==>>" + week);
test = false;
} else {
Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
System.out.println("Week==>>" + week);
test = true;
}

How does cal.setTime (new Date()); work?

I want to use the cal.setTime (new Date()); in my code to update the time, but it dosent work.
import javax.swing.JOptionPane;
public class Exercise2b {
public void demo() {
String message1, message2;
int hour, minute, second;
Time dt = new Time();
hour = dt.getHour();
minute = dt.getMinute();
second = dt.getSecond();
message1 = "The clock is " + minute + " minutes over " + hour + " (+"
+ second + " seconds)";
message2 = dt.toString();
JOptionPane.showMessageDialog(null, message1);
JOptionPane.showMessageDialog(null, message2);
dt.update();
message2 = dt.toString();
JOptionPane.showMessageDialog(null, message2);
}
public static void main(String[] args) {
Exercise2b prog = new Exercise2b();
prog.demo();
}
}
import java.util.Calendar;
import java.util.Date;
public class Time {
private Calendar cal;
private int hour;
private int minute;
private int second;
public Time() {
cal = Calendar.getInstance();
this.hour = cal.get(Calendar.HOUR_OF_DAY);
this.minute = cal.get(Calendar.MINUTE);
this.second = cal.get(Calendar.SECOND);
}
public int getHour() {
return this.hour;
}
public int getMinute() {
return this.minute;
}
public int getSecond() {
return this.second;
}
public String toString() {
return hour + ":" + minute + ":" + second;
}
public void update() {
cal.setTime (new Date());
}
}
I suspect the issue is that you set the cal variable but not the hour/minute/seconds variables that are set from the initial value of `cal in the constructor.
This is an example of DRY (don't repeat yourself). In this situation it's easy to get in an inconsistent state. I would simply have your accessor methods query the cal object directly (instead of using the intermediary variables). And perhaps investigate the Joda library for a better / more reliable date/time API.
The problem is that when you call the update() method you are not refreshing the values of the local variables (second/ minute / hour). Those are already initialized from the constructor.
How does cal.setTime (new Date()); work?
The javadoc states
Sets this Calendar's time with the given Date.
new Date() creates a new Date object with the millisecond value of System.currentTimeMillis().
So
cal.setTime (new Date());
will replace the internal millisecond value of cal to that of the new Date object.

Categories