I'm quite new to Android and I want to change (I know how to set it dynamically but....)Textview Dynamically after a certain period of Days,but int the meantime keep the text posted unless changed by user or if a certain days have been reached by my program.
Well Basically I have the user to input a Date then i want my program to count days and as long as the user nor my program have intervene with the textview it will show the same text and backround color until the opposite is taken action.
here is my code:
String CurrentDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
String FinalDate = TvDateOfService.getText().toString();
SimpleDateFormat dates = new SimpleDateFormat("dd/MM/yyyy");
Date dateinput;
Date datetwra;
//Setting dates
try {
dateinput = dates.parse(FinalDate);
datetwra = dates.parse(CurrentDate);
//Comparing dates
long difference = Math.abs(dateinput.getTime() - datetwra.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
//Calendar Instance to Add 89 Days for Service Period Between Dates!!
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DATE, 90);
Date ServicePeriod = cal1.getTime();
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.DATE, 80);
Date DaysBeforeEnd = cal2.getTime();
do {
tvStatus.setBackground(getApplicationContext().getResources().getDrawable(R.drawable.textview_backround_green));
}while (dateinput.before(DaysBeforeEnd));
do {
tvStatus.setText("something");
tvStatus.setBackground(getApplicationContext().getResources().getDrawable(R.drawable.textview_backround_yellow));
}while (dateinput.after(DaysBeforeEnd));
do {
tvStatus.setText("something else");
tvStatus.setBackground(getApplicationContext().getResources().getDrawable(R.drawable.textview_backround_red));
}while (dateinput.after(ServicePeriod));
It looks like you're trying to use a for loop and wait a certain number of days - it would be most beneficial to the phone's battery if you used AlarmManager
https://developer.android.com/trai.../scheduling/alarms.html
Related
Time 1 : 10:30 06/05/2018
Time 2 : 19:45 06/05 2018
I want to pick a random time between these two time. The result may be (13:15 06/05/2018).
I look into Calendar but seem it does not support a method like range(time1, time2)
What is the solution for this case ? Thanks.
I would use something like this.
public static Calendar getRandomTime(Calendar begin, Calendar end){
Random rnd = new Random();
long min = begin.getTimeInMillis();
long max = end.getTimeInMillis();
long randomNum = min + rnd.nextLong()%(max - min + 1);
Calendar res = Calendar.getInstance();
res.setTimeInMillis(randomNum);
return res;
}
if you have API 21+, use ThreadLocalRandom
public static Calendar getRandomTime(Calendar begin, Calendar end){
long randomNum = ThreadLocalRandom.current().nextLong(begin.getTimeInMillis(), end.getTimeInMillis() + 1);
Calendar res = Calendar.getInstance();
res.setTimeInMillis(randomNum);
return res;
}
you should convert your times objects to long first as follows (I suppose that you have two Calendar objects already)
long time1InLong = time1.getTimeInMillis();
long time2InLong = time2.getTimeInMillis();
Then you can use following code to generate random number
Random r = new Random();
long randomTime = r.nextLong(time2InLong - time1InLong) + time1InLong;
Then you can convert this randomTime back to Calendar as follows
// Create a DateFormatter object for displaying date in specified format.
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm dd/MM/yyyy");
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(randomTime);
Adding Events for all days between start date and end date in google calendar Android. i want remainder every 3 months till end date.
This is my function
public void addEvent1(Context ctx, String title){
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
Date Startdate = null;
Date Enddate =null;
String dtStart = date.getText().toString();
try {
Startdate = df2.parse(dtStart);
Enddate = df2.parse(stringMaturityDate);
Log.v("SDate: ",""+ df3.format(Startdate));
Log.v("EDate: ",""+ df3.format(Enddate));
} catch(ParseException e){
e.printStackTrace();
}
Calendar cali = Calendar.getInstance();
cali.setTime(Startdate);
Calendar cali2 = Calendar.getInstance();
cali2.setTime(Enddate);
SimpleDateFormat yyyymmdd = new SimpleDateFormat("yyyyMMdd");
Calendar dt = Calendar.getInstance();
dt.setTime(Enddate);
String dtUntill = yyyymmdd.format(dt.getTime());
ContentResolver contentResolver = ctx.getContentResolver();
ContentValues calEvent = new ContentValues();
calEvent.put(CalendarContract.Events.CALENDAR_ID, 1); // XXX pick)
calEvent.put(CalendarContract.Events.TITLE, title);
calEvent.put(CalendarContract.Events.RRULE, "FREQ=MONTHLY;INTERVAL=3;UNTIL=" + dtUntill);
calEvent.put(CalendarContract.Events.DTSTART, cali.getTimeInMillis());
calEvent.put(CalendarContract.Events.DTEND, cali2.getTimeInMillis());
calEvent.put(CalendarContract.Events.EVENT_TIMEZONE, "" + java.util.Locale.getDefault());
Uri uri = contentResolver.insert(CalendarContract.Events.CONTENT_URI, calEvent);
int id = Integer.parseInt(uri.getLastPathSegment());
Toast.makeText(ctx, "Created Calendar Event " + id,
Toast.LENGTH_SHORT).show();
ContentValues reminders = new ContentValues();
reminders.put(CalendarContract.Reminders.EVENT_ID, id);
reminders.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
reminders.put(CalendarContract.Reminders.MINUTES, 10);
Uri uri1 = contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, reminders);
}
this function adds events every day. How to remove that. I need only remainder.Is there any anything wrong in my code??
If I read everything correctly you want a calendar item every tree months for one full day. Have you tried adding this line?
contentValues.put(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
And changed the end date of one calendar item is currrently set to the end of the year while this should be the end date of the current item. DTEND is the end of the current item DURATION is the end of the reoccuring patern.
If I understood the problem wrong please give me a detailed description. For all options in the CalenderContracts check this link.
EDIT:
You want a calendar appointment for each day but remind the user every three months. With your code this is not currently possible as you are adding a reminder for every calender item with that id (so for every day). Only easy solution what I can think of is creating a separate appointment with an other id that you repeat every three months with an reminder and a different id. It is not currently possible to set an alarm for some events with the same id and some not.
I have a custom dialog with a datepicker and a time picker in it. The user sets the Date which all works fine. The date picker is the hidden and the time picker is shown. I am currently setting the time on the timepicker manually to 8 am.
I now want to convert the user set time in the time picker to a long which I am able to do however its showing me the current time on the phone in the logcat and not the actual set time... Thanks!
button_continue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (timeset == false) {
Calendar calendar = Calendar.getInstance();
calendar.set(datePickerDiet.getYear(), datePickerDiet.getMonth(), datePickerDiet.getDayOfMonth());
long startTime = calendar.getTimeInMillis();
System.out.println(startTime);
// save to shared pref
ProfilePrerences.getInstance().setLongValue(DietActivity.this, ProfilePrerences.KEY_START_DIET_DAY, startTime);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(startTime));
System.out.println(dateString);
datePickerDiet.setVisibility(View.GONE);
time_breakfast.setVisibility(View.VISIBLE);
dialog_txt.setText("At what time do you have breakfast?");
time_breakfast.setCurrentHour(8);
time_breakfast.setCurrentMinute(0);
time_breakfast.clearFocus();
timeset = true;
}
else if (timeset == true) {
// time_breakfast.setVisibility(View.VISIBLE);
Calendar calendar2 = Calendar.getInstance();
calendar2.set(time_breakfast.getCurrentHour(), time_breakfast.getCurrentMinute(), 0);
long breakfasttime = calendar2.getTimeInMillis();
System.out.println(breakfasttime);
SimpleDateFormat formatter2 = new SimpleDateFormat("hh:mm");
String dateString2 = formatter2.format(new Date(breakfasttime));
System.out.println(dateString2);
// startdietdialog.cancel();
ProfilePrerences.getInstance().setLongValue(DietActivity.this, ProfilePrerences.KEY_BREAKFAST_TIME, breakfasttime);
timeset = false;
}
}
});
This line is causing you the problem:
calendar2.set(time_breakfast.getCurrentHour(), time_breakfast.getCurrentMinute(), 0);
This is setting the year, month, day on calendar2 - not the hour, minute, second you intended.
Probably the easiest solution is call the direct methods - setHour, setMinute, etc., on calendar2.
Two things: you're printing the current date (new Date):
String dateString2 = formatter2.format(new Date(breakfasttime));
System.out.println(dateString2);
You have to print calendar2 time:
String dateString2 = formatter2.format(calendar2.getTime());
System.out.println(dateString2);
The other is, Greg Ennis said, you're setting calendar2 time incorrectly: there is not such method to set only the hour, minutes and seconds. You should set year, month and day also or call set(Calendar.HOUR, h), set(Calendar.MINUTE, m), etc separately
It can be the similar question that I have found in StackOverFlow. But I have a little bit different situation then all of them. In my database I have start Date and Start Time. I want the system compare it's date and time separately because starting date and time are in separate columns in database. First the system compares the date and then time. The another activity should open only if the date is same and the time is before 15 minutes the starting time in database.
I have done this so far;
private void startTraining() {
Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyy");
String currentDate = formatter.format(calendar1.getTime());
System.out.println(currentDate);
Calendar calendar2 = Calendar.getInstance();
SimpleDateFormat formatter2 = new SimpleDateFormat("hh:mm");
String currentTime = formatter2.format(calendar2.getTime());
System.out.println(currentTime);
String trainingStartDate = SharedMemory.getInstance()
.getCurrentTraining().getDate();
String trainingStartTime = SharedMemory.getInstance()
.getCurrentTraining().getStartTime();
int difference = trainingStartTime.compareTo(currentTime);
System.out.println(difference);
//System.out.println(trainingStartTime);
if (currentDate.toString().equals(trainingStartDate)&& difference < 15) {
Log.i("Debug", "CHECKPOINT");
Intent intent = new Intent(getApplicationContext(),
TraineeListActivity.class);
MainActivity.this.startActivity(intent);
finish();
} else{
}
}
I am not getting the result what I am expecting. Thanks in advance.
You use String.compareTo() to compare the "time" String, which won't work correctly. Try changing the code to this
private void startTraining() throws ParseException {
// current date & time
Calendar now = Calendar.getInstance();
// parse date & time from database
String trainingStartDate = SharedMemory.getInstance()
.getCurrentTraining().getDate();
String trainingStartTime = SharedMemory.getInstance()
.getCurrentTraining().getStartTime();
String strDateTime = trainingStartDate + " " + trainingStartTime;
Calendar training = Calendar.getInstance();
training.setTime(new SimpleDateFormat("MM-dd-yyyy kk:mm")
.parse(strDateTime));
// find difference in milliseconds
long difference = training.getTimeInMillis() - now.getTimeInMillis();
if (difference < 15 * 60 * 1000) { //less than 15 minutes
Log.i("Debug", "CHECKPOINT");
Intent intent = new Intent(getApplicationContext(),
TraineeListActivity.class);
MainActivity.this.startActivity(intent);
finish();
} else {
}
}
public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
LINE 5:
private String compareStringOne = String.valueOf(SetTimeActivity.intFromTimeH)+ ":"+ String.valueOf(SetTimeActivity.intFromTimeM) ;
LINE 6:
private String compareStringTwo = String.valueOf(SetTimeActivity.intToTimeH) + ":"+ String.valueOf(SetTimeActivity.intToTimeM);
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates()
{
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if (!(dateCompareOne.before( date ) && dateCompareTwo.after(date))) {
....
I am trying to check if current time falls between the specified time. For that I am converting the specified time into strings first (in Line5 & Line6). Even though I get the integer values correct, the string formed always shows "0:0".
Also, the year is shown as 1970 (The date & the day shown are wrong as well).
I need to get the current time. What am I doing wrong?
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
The parseDate() function returns the time elapsed since the 1st of January 1970. This is known as the Unix Epoch, and it's how all time is represented in Unix computers. By running the parseDate function on a string containing just hours and minutes, you're creating a Date object which represents a time HH:mm past the first of January 1970.
Your code is using a really odd way of getting the current time. Converting a Calendar to two ints, then to a string and finally parsing back to a Date is going to be inefficient and open you up to all sorts of needless errors.
When you initialise a new Date object it is automatically assigned the time of initialisation. Therefore:
Date d = new Date();
would result in d being the moment of initialisation (that is, this year, month, day, hour, minute, second and microsecond). Then you can just use Date.after() and Date.before().
If you still want to do it via the Calendar method, then you'd be better served by:
cal = Calendar.getInstance();
Date d = cal.getTime();
It may be that you've got other issues, but it's worth doing it properly first. When you pass data by writing it as a string (especially when it's time related, with all sorts of ambiguities about what "12" actually represents) you lose all the advantages that language typing gives you.
this code help you
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE); if (c.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (c.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
// Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String formattedDate = df.format(c.getTime());
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
If you already work with Date objects why not using the Date.after(...) and Date.before(...) methods.