How to Run AsyncTask at a certain time from a Activity? - android

I have an AsyncTask in a activity that i only want to run once a week. How do i go about doing this?
I am retrieving a list of URL's about 7 of them and then putting them in SharedPreference.
i only want to update and check for new URL's once a week from my activity. This will be in my Main Activity.

You could save the date when you use the asynctask in the shared preferences.
So whenever the Main Activity starts you can check the current date and the date in the shared preferences, if its more than 7 days, you can do your asynctask again and update the saved date to the current date.
I believe you already know how to put strings inside shared preferences and to access them.
This is just the basic code of what to do. You will need to modify it a bit to get it working for you.
private static String getToday(){
Calendar objCalendar = new GregorianCalendar(Calendar.getInstance().getTimeZone());
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
return objFormatter.format(objCalendar.getTime());
}
private static String getAfter7DaysDate(){
Calendar objCalendar = new GregorianCalendar(Calendar.getInstance().getTimeZone());
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
objCalendar.add(Calendar.DATE, 7);
return objFormatter.format(objCalendar.getTime());
}
public int daysBetween(Date d1, Date d2){
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}
If you put this in the onCreate
String today = getToday();
String afterSevenDate = getAfter7DaysDate();
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
try {
Log.e(today,Integer.toString(daysBetween(objFormatter.parse(today),
objFormatter.parse(afterSevenDate))));
} catch (ParseException e) {
e.printStackTrace();
}
The above code just retrieves the current date, the date after 7 days, and also find the difference in days between the 2 dates. You will need to get the saved date and find the after 7 days date and check if the differnce between the current date is >= to 7. If its true, do your async task.
This is the simple way to do it.
As JoeLallouz mentioned this will only work if user goes to that activity. But it will work even if he opens after a month due to the >= checking. But if you need to do it even if the user doesn't open you're app, you will need to look into the AlarmManager class.

Related

Android - Setting date to RelevantDate with an CursorAdapter

Let me just give an example of the requirements I am trying to fulfill. (Sorry if it's kind of a dumb question but my brain is a little fried right now and I'm working on this by myself)
I have a CursorAdapter (w/ SQLite on the backend) that I am using for my ListView to display content. One of the fields in the list item that I am displaying is the date the item was added to the Listview. So...
CASE:
If today was December 31st, 2013 and I just created a list item I would like it to display "Today". On January 1st, 2014 I would like the date to change to "Yesterday". And finally, on January 2nd, 2014 I would like the date to change to "12/31/2013".
What is the simple or most elegant way of fulfilling these requirements? I don't want to be constantly checking my whole listview for dates and be mean to the CPU. Any ideas on the best practice of saving the date would also be much appreciated!
Thanks!
I think I've got it working... I use this method in the activity where my listview is and call it every onCreate, onStart, and onResume.
public void setRelevantDate() {
SimpleDateFormat year = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Date date = new Date();
String current_date = year.format(date);
String db_day_after_creation_date;
//check dates created, sub "today" or "yesterday"
for(SoundData s: app.unsent_recordings){
Log.e("soundData date flag",String.valueOf(s.isAfter_Day_two()));
Log.e("soundData date buffer",s.getDate_buffer());
Log.e("soundData date created",s.getDate_created());
if (!s.isAfter_Day_two()){ //if we are two days after the creation then we can skip all the checks for this item because
// it has already been set back to the initial MM/dd/yyyy date format
String sql_date = s.getDate_buffer();
String db_date = sql_date.substring(0,10);
String db_time = sql_date.substring(11);
//find the day after creation date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(db_date));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, 1);
db_day_after_creation_date = sdf.format(c.getTime());
if (db_date.equals(current_date)){
s.setDate_created("Today, "+db_time);
app.update_Recording_DateCreated(s.getId(),"Today, "+db_time, s.getDate_buffer(), String.valueOf(s.isAfter_Day_two())); //dateCreated = today, TIME
}
else if(current_date.equals(db_day_after_creation_date)){ // basically if the current date is equal to the day after the db_created date
s.setDate_created("Yesterday, "+db_time);
//we can say that it was created yesterday
app.update_Recording_DateCreated(s.getId(),"Yesterday, "+db_time, s.getDate_buffer(), String.valueOf(s.isAfter_Day_two()));
}
else{
s.setDate_created(sql_date);
//Otherwise use normal date
app.update_Recording_DateCreated(s.getId(),sql_date,s.getDate_buffer(), String.valueOf(s.isAfter_Day_two())); //dateCreated = dateBuffer
}
app.mCursor = app.db.getCursor();
app.rec_adapter.changeCursor(app.mCursor);
app.rec_adapter.notifyDataSetChanged(); //Update cursor, notifyDataSetChanged()
}

Formatting Long value to Date String?

I am working on an application in which I have to convert a long value to a Date string and display. To achieve the purpose I am using following function, but it is returning me the date from 70's and 80's obviously not appropriate. I am using the following finction:
public static String convertDateFromLongToCompleteString(long date) {
Date d = new Date(date * 1000);
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
String formattedDateFromLong = dateformat.format(d);
return formattedDateFromLong;
}
The long value is just simply System.currentTimeMillis() and when I have to show it to the user, I have to format that for which I am using above function. I have checked system and device dates, their zones and time, everything is just fine. Please update that why is this issue appearing and how can I get the exact date. Thanks!
Edit
I have also tried withoout multiplication with 1000, it gives me time and date from 1970.
If your long date is simply System.currentTimeMillis(), then multiplication with 1000 is not required.
Date d = new Date(date);
Replace Date d = new Date(date * 1000); with Date d = new Date(date);
In case you're using the above method only with System.currentTimeMillis(), you can call Date constructor without any parameters, it will give you the Date object that refers to the current date and time. This will be an easier way to solve your problem. Hope this helps.

Getting number of days difference between 2 dates

I am using jxl api to read an excel file in android. When I get a date like "30/11/2012" from excel, the LabelCell output shows me date as "11/30/12".
1) I need to get the output in dd/MM/yyyy format when reading the excel file, because it exists that way in excel, so I wouldn't want to unnecessarily convert it into another format. How to do that ?
2) After reading in the excel column's date, I generate 2 variables, one which has excel date - 20 days (lets call it excelMinus20) and another excel date + 10 days (lets call it excelPlus10.
Now, I would like to check going further, if the current system date (smartphone's date) >= excelMinus20 and current system date <= excelPlus10.
How to do this whole thing using java.text.Date ? I tried using joda time as well, but it's too complicated to use. Please guide me at least in the right direction.
Thanks in advance
Omkar Ghaisas
To parse your date from text format:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("30/11/2012");
More info : SimpleDateFormat doc
To substract days from your date:
public static Date substractDays(Date date, int days)
{
long millis = date.getTime();
long toSubstract = days * 1000 * 60 * 60 * 60 * 24;
// 1milli 1s 1m 1h 1d
return new Date(millis-toSubstract);
}
Adding some days would be the same, except replace - with +
To get back a String representation from a Date object:
DateFormat formatter = new SimpleDateFormat("...pattern...");
String formatedDate = formatter.format(date.getTime());
EDIT:
You could also do the Date adding/substracting with the method you suggested:
public static Date substractDays(Date date, int days)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -20 /*or +10*/);
return calendar.getTime();
}
If you want to check if a Date is in an interval, then:
public static boolean isInInterval(Date date, Date from, Date to)
{
return date.getTime()<to.getTime() && date.getTime() > from.getTime();
}

How to compare two timestamps in android?

I want to compare two timestamps and if the difference of that is (-+5minuts) then I want to display alert dialog.
i.e. If currently in our watch 4PM the second time is 4.05PM or 3.55PM then alert will display else not.
Can anyone suggest me the way how can I get the solution of this.??
I found after search the function of getting timeStamp and how to compare two timestamps but for this type of condition is there any method or function?
Thanks.
My code is:-
date= new Date();
currentTime = date.getTime();
if(currentTime !=0 && previousTime !=0){
String result = (String) DateUtils.getRelativeTimeSpanString(currentTime, previousTime, 0);
}
And I am storeing current time in to previous time lilke tis way :-
if(currentTime != previousTime){
previousTime = currentTime;
}
There's two approaches you could take, depending on whether you just want to measure time elapsed, or want to set future times to compare to.
The first is similar to Sourabh Saldi's answer, record the result from
long prevEventTime = System.currentTimeMillis();
then compare it with System.currentTimeMillis() until the difference is more than 300000
As you have mentioned, your timestamp from the server is in milliseconds since January the 1st, 1970. This means it is directly comparable to System.currentTimeMillis(). As such, use:
long serverTimeStamp=//whatever your server timestamp is, however you are getting it.
//You may have to use Long.parseLong(serverTimestampString) to convert it from a string
//3000(millliseconds in a second)*60(seconds in a minute)*5(number of minutes)=300000
if (Math.abs(serverTimeStamp-System.currentTimeMillis())>300000){
//server timestamp is within 5 minutes of current system time
} else {
//server is not within 5 minutes of current system time
}
The other method looks closer to what you're already doing - using the Date class to store the current and compared time. To use these, you'll want to be using the GregorianCalendar class to handle them. Calling
calendar=new GregorianCalendar();
will create a new calendar, and automatically set it's date to the current system time. You can also use all the functions supplied in the GregorianCalendar class to roll the time forward or backward using something of the form
calendar.add(GregorianCalendar.MINUTE, 5);
or set it to a Date object's time with
calendar.setTime(date);
In your case, depending on how much flexibility you want both the GregorianCalendar class and the Date class have after() methods, so you probably want something like the following:
Create somewhere:
Date currentDate=newDate();
Then set your alarm point:
calendar=new GregorianCalendar(); //this initialises to the current system time
calendar.setTimeInMillis(<server timestamp>); //change to whatever the long timestamp value from your server is
calendar.add(GregorianCalendar.MINUTE, 5); //set a time 5 minutes after the timestamp
Date beforeThisDate = calendar.getTime();
calendar.add(GregorianCalendar.MINUTE, -10); //set a time 5 minutes before the timestamp
Date afterThisDate = calendar.getTime();
Then check if the current time is past the set alarm point with
currentDate.setTime(System.currentTimeMillis());
if ((currentDate.before(beforeThisDate))&&(currentDate.after(afterThisDate))){
//do stuff, current time is within the two dates (5 mins either side of the server timestamp)
} else {
//current time is not within the two dates
}
This approach can seem a bit more long winded, but you'll find it is very robust and flexible, and can easily be extended to set alarm points far in the future, or use the GregorianCalendar methods to easily set dates hours, days or weeks into the future.
How about just:
private static final long FIVE_MINUTES = 1000 * 60 * 5; //5 minutes in milliseconds
long currentTime = new Date().getTime();
long previousTime = mPreviousTime;
long differ = (currentTime - previousTime);
if (differ < FIVE_MINUTES && differ > -FIVE_MINUTES ){
// under +/-5 minutes, do the work
}else{
// over 5 minutes
}
long etime = 0;
final long time1 = uptimeMillis();
/* do something */
final long time2 = uptimeMillis();
if (time2 < time1) {
etime = Long.MAX_VALUE - time1 + time2;
} else {
etime = time2 - time1;
}
then check this etime and do as required!!1
Use this following method to change your dates in epoch format
public Long getChnagedDate(Activity act,String date) throws ParseException
{
long epoch = new java.text.SimpleDateFormat ("MM/dd/yyyy HH:mm:ss aa").parse(date).getTime();
return epoch/1000;
}
and after check the difference in http://www.epochconverter.com.
Hope it helps you.
Joda time will help you with this task.
import org.joda.time.Interval;
http://joda-time.sourceforge.net/

Change date format to System's current format retrieved through database in Android

I have stored date in database,
first take the current date then convert it into String then store it into database,
it is working fine.
Then I want to retrieve the data and show it to ListView,
for that i did:
// get the string value of date
String dateString = c.getString(c.getColumnIndex(CallHistoryDataBase.colDate));
// format according to system's current format
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
textViewDateTime.setText(dateFormat.format(new Date(dateString)));
It is working fine,
like if I have stored date with "dd/MM/yyyy" format
and later I have changed the System's format to "yyyy/MM/dd"
in list it showing with "yyyy/MM/dd" format.
But some time it displays 2014/04/14 for date 2012/04/14.
I have checked, at the time of storing and retrieving data to and from database it is fine.
I don't get any clue. There is no hard code, not even 14 number is there.
Any suggestion...
different solution is also acceptable.
public String getDate(final Context context, final long time) {
long t = time;
if (t < MIN_DATE) {
t *= MILLIS;
}
final Calendar base = Calendar.getInstance();
base.set(Calendar.HOUR_OF_DAY, 0);
base.set(Calendar.MINUTE, 0);
base.set(Calendar.SECOND, 0);
if (t < base.getTimeInMillis()) {
SimpleDateFormat df1 = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate1 = df1.format(t);
return formattedDate1;
// return DateFormat.getDateFormat(context).format(t);
} else {
return DateFormat.getTimeFormat(context).format(t);
}
}
by using this method you can get date in dd-mm-yyyy formate.And pass data in database as millisecond time.
Hope its useful for you.

Categories

Resources