Date not storing after iteration - android

I have an iteration that runs for a set number of times depending on another value which can vary which is why I'm using an iteration that iterates based on that value, inside that iteration I add 30 days to a date once each iteration and then add the results to a table.
PROBLEMS
I simply end up with the first instance of adding 30 days which is outside the iteration itself. This means that my values inside the iteration are not being stored properly but I can't see why.
I've checked the DateTime operations and displayed the value of newdate and it shows the proper date so it's most likely the storing of the date. But I don't know what's going wrong, it works pre-iteration which is what's got me confused. Why isn't it executing inside the iteration? Does anyone have any idea?
Ex.
InitialDate | 3/29/2015
2ndDate | 4/28/2015<-- This is what's stored which is pre-iteration
3rdDate | 5/28/2015<-- This is what it's supposed to be after the iteration
so on and so forth....
Values pre-iteration
//Date stuff
String startdate = (String.valueOf(Acc._date));
DateTimeFormatter formatter = DateTimeFormat.forPattern("MM-dd-yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(startdate);
DateTime startpoint = new DateTime(dt);
DateTime whendue = startpoint.plusDays(30);
DateTime foriteration = whendue;
String formattedDate = whendue.toString(formatter);
//Storing initial date
pay.setDateDue(formattedDate);
db.AddPayment(pay);
Actual iteration
while (i < j) {
//Operation for Date Calculation
DateTime ndt = foriteration.plusDays(30);
foriteration = ndt;
String newdate = ndt.toString(formatter);
//Adding values to PayTable
pay.setDateDue(newdate);
db.AddPayment(pay);
i++;
}

Finally found out what was wrong. Nothing. My roommate played a prank on me and just got back from his trip out of town and explained to me how he changed my getDateDue to execute a plusDays(30) to mimic my code so that when I called AddPayment which calls getDateDue it would look like it would work but in actuality would only add 30 days once to the startdate no matter what I did.
Summary
Roommate is an ass, nothing is wrong with my code. Sorry for this pointless post.

Related

MPAndroidChart x date value duplication problem

I am implementing the function to display the change of exercise time by date as a graph.
But there was a problem.
Before I explain the problem, I will briefly explain my code.
When a date is input from the user, the date is stored in the database and output by date.
For example, when the user enters 2020/06/26, it is displayed as 06/26 on the graph.
Now I will explain the problem.
The x value of the graph is overlapping. 07/01 does not appear immediately after 06/30, but very far.
I will attach my code and execution result. enter image description here
xAxis.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
Date date = null;
try {
date = simpleDateFormat.parse(Float.toString(value));
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd");
String dateString = newFormat.format(date);
return dateString;
}
});
Hard to tell from the code you provide. But most probably, the problem does not lie in the ValueFormatter, but in the actual x values you use. Having x values in the format yyMMdd ist most likely not what you want, because the difference between e.g. 2020-04-01 and 2020-04-02 is not the same as between 2020-03-31 and 2020-04-01, event if it should be exactly the same (1 day). You should use another representation for the x values, e.g. "days since 1970".
This still does not explain why 06-30 is displayed after 07-01 and even after 08-19, however. My guess is that your Entry list is not sorted properly in ascending order.

How to compare the current date with string date stored in array?

I am trying to compare the current date with the date stored in the array, but I am not able to compare the date using if condition.
I use this code to compare the date:
DateFormat TO = new SimpleDateFormat("yyyy-MM-dd ");
Today = TO.format(Calendar.getInstance().getTime());
for (int i = 0; i < jsonArray.length(); i++) {
// Today has a value 2018-03-13
// ScheduleDates[i] has a value 2018-03-13
// ScheduleDates[10] has a value 2018-03-13
if (Today.equals(ScheduleDates[i])) {
Toast.makeText(Main2Activity.this, "Match Found" + ScheduleDates[i] + "--"
+ StartTimes[i] + "--" + Endtimes[i], Toast.LENGTH_LONG).show();
break;
} else {
Toast.makeText(Main2Activity.this, "Match Not Found", Toast.LENGTH_LONG).show();
break;
}
}
But when I run the loop it shows only "match not found". I cannot find what error I had made, can anyone help to find the error?
Use Log.d("Today",String.valueOf(Today)); to see what is in your Today variable. Also use
for(int i=0;i<jsonArray.length();i++){
Log.d("Array",String.valueOf(ScheduleDates[i]));
}
Try to verify with your own eyes using the logcat that the exact date that is stored in your Today variable also exists in your array. If not, there is your problem. Your if statement works just fine, there just isn't any date in the array that is the same with the one in Today.
Edit: It is not visible in your code but i am willing to acept that jsonArray and ScheduleDates have the same length and that the second derives from the first. Otherwise your for loop would crash.
Edit2: Your problem actually is your break statements . Your for loop only runs once, so if the first item of the array matches the date in Today it stops and prints your success message. If the first item of your array does not match the date in Today it again stops and prints the failure message which is also the case as you have said.
So, remove the break statements and then the for loop will run as many times as it should and print the appropriate message whether it is for success or failure.
If you just want to find the first match and then stop, remove the break statement in your else but keep the one in your if.
only remove extra space define in date format like below ...
DateFormat TO = new SimpleDateFormat("yyyy-MM-dd");

why my code is so slow?

i runing this code on android after load a cursor with the query i pass to the adapter, but my date is in long in milliseconds format so i need to format properly before load the adapter!
problem is this code is taking 14 seconds to pass a 50 items load, the problem get worst if i call it inside the adapter getView cause get slow when i scrool, if i take this function out the program runs smoothly
this is call inside my listfragment
private String dateFormatPatternEdited(long timeMS) {
android.text.format.DateFormat df = new android.text.format.DateFormat();
final Calendar eDate = Calendar.getInstance();
Calendar sDate = Calendar.getInstance();
sDate.setTimeInMillis(timeMS);
long daysBetween = 0;
while (sDate.before(eDate)) {
sDate.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
String mDateFormatPattern = FuelTrackerApplication.dateFormat.format(timeMS);
if (daysBetween < 2){
mDateFormatPattern = FuelTrackerApplication.timeFormat.format(timeMS);
} else if(daysBetween < 365){
mDateFormatPattern = df.format(FuelTrackerApplication.dateFormatPattern,timeMS).toString();
}
return mDateFormatPattern;
}
and this is were i initialize the date formats i gonna use its called inside onCreate in FuelTrackerApplication i dont think theres nothing wrong with this
public void initializeDateFormat() {
android.text.format.DateFormat df = new android.text.format.DateFormat();
dateFormatPattern = "MMM dd";
if (android.os.Build.VERSION.SDK_INT >= 18){
dateFormatPattern = df.getBestDateTimePattern(Locale.getDefault(), dateFormatPattern);
}
dateFormat = df.getMediumDateFormat(getApplicationContext());
timeFormat = df.getTimeFormat(getApplicationContext());
dateFormat2 = df.getLongDateFormat(getApplicationContext());
}
Ok just a few things. Depending on how long ago your dates are going back. You are only interested if the days between go more then 365. So if your dates are going back for years, you're doing extra work.
while (sDate.before(eDate) && daysBetween <= 365) {
sDate.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
Will let it break, it means if you have 20 entries going back 5 years, you don't do so much work.
It might be worth while to possibly just check the milliseconds difference. I'm not sure if this is precise enough, but it should work. It means you don't need to loop everything E.g
long millisecondsToday = getMilliseconds;
long timeMs = // you already have this
long millisecondsDifference = millisecondsToday - timeMs;
if (millisecondsDifference < MILLISECONDS_TWO_DAYS) // set a final variable out of this method
// etc
If might also be worth while initialising some of your variables once outside of the method. Like your df, that is being created 50 times, and then just having something set on it. Same with your eDate.
i got this incredible faster and practicaly remove the hole function
instead goes like this
lDateBetween = NOW - timeMS;
if (lDateBetween < DAY)
return FuelTrackerApplication.timeFormat.format(timeMS);
else if (lDateBetween < YEAR)
return df.format(FuelTrackerApplication.dateFormatPattern,timeMS).toString();
else return FuelTrackerApplication.dateFormat.format(timeMS);
all calculation is made using milliseconds i also put 2 final NOW and YEAR, also df and lDateBetween
i think is the fastest i can get!

I cannot print more than 25 dates, it somehow goes crazy and continues from another date, why?

I have a datepicker, and I pick up two dates, like 2012-04-08 and 2012-05-11. Because I have a database and need store dates as strings I convert them to 20120408 and 20120511 (strings so far). My code contains the next steps. I call my function with these strings:
public void durva(String datefrom, String dateto) throws ParseException {
datefrom = GlobalVars.getDateStringFrom();
dateto = GlobalVars.getDateStringTo();
Log.i("DateFrom", datefrom);
Log.i("Dateto", dateto);
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyyMMdd"); //-de most yyMMdd
formatter2.setLenient(false);
Date dates1;
Date dates2;
long mili1;
long mili2;
long diff;
String dates="";
String convertedDates = "";
dates1 = formatter2.parse(datefrom);
mili1 = dates1.getTime();
Log.i("date1", String.valueOf(mili1));
dates2 = formatter2.parse(dateto);
mili2 = dates2.getTime();
Log.i("date2", String.valueOf(mili2));
diff = 1+((mili2-mili1)/86400000);
Log.i("diff", String.valueOf(diff));
long [] millis = new long[(int) diff];
for (int i=0;i<diff;i++)
{
millis[i] = mili1+(86400000*i);
Log.i("millii", String.valueOf(millis[i]));
dates = dates + String.valueOf(millis[i]) + " ";
SimpleDateFormat formatterX = new SimpleDateFormat("yyyyMMdd");
String dateString = formatterX.format(new Date(millis[i]));
convertedDates = convertedDates + dateString + " ";
}
Log.i("DATES", convertedDates);
}
I use the a created GlobalVars when I pick a date and covert them to this string format I mentioned above. Then I convert them to millisecs. Then I convert them back to my format but it is not important, since the millisecs are already messed up. With
for (int i=0;i<diff;i++)
{
millis[i] = mili1+(86400000*i);
Log.i("millii", String.valueOf(millis[i]));
I always increase the millisecs, but what happens after the 25th value? It travels back in time and continues from another value! In this example I get: 20120408 20120409 .. 20120502 20120314..20120322 . I add 86400000 (millisecs per day) for jumping a whole day.
What's happening here?
Thank you in advance!
You should use 86400000L, or declare i as long:
millis[i] = mili1+(86400000L*i);
Otherwise both i and 86400000 are 32 bit integers, so the result is calculated as a 32-bit integer. Unfortunately 86400000*25 is too big to fit in 32 bits, so it wraps around.
86400000*25 is -2134967296.
Another thing you should be careful about is that not all days have 24 hours thanks to DST.

Cannot get Correct month for a call from call log history

I am trying to extract information from the call log of the
android. I am getting the call date that is one month back from the
actual time of call. I mean to say that the information extracted by
my code for the date of call is one mont back than the actual call
date.
I have the following in the Emulator:
I saved a contact. Then I made a call to the contact.
Code:
I have 3 ways of extracting call Date information but getting the same
wrong result. My code is as follows:
/* Make the query to call log content */
Cursor callLogResult = context.getContentResolver().query(
CallLog.Calls.CONTENT_URI, null, null, null, null);
int columnIndex = callLogResult.getColumnIndex(Calls.DATE);
Long timeInResult = callLogResult.getLong(columnIndex);
/* Method 1 to change the milliseconds obtained to the readable date formate */
Time time = new Time();
time.toMillis(true);
time.set(timeInResult);
String callDate= time.monthDay+"-"+time.month+"-"+time.year;
/* Method 2 for extracting the date from tha value read from the column */
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
String Month = calendar.get(Calendar.MONTH) ;
/* Method 3 for extracting date from the result obtained */
Date date = new Date(timeInResult);
String mont = date.getMonth()
While using the Calendar method , I also tried to set the DayLight
SAving Offset but it didnot worked,
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
int DST_OFFSET = calendar.get( Calendar.DST_OFFSET ); // DST_OFFSET
Boolean isSet = calendar.getTimeZone().useDaylightTime();
if(isSet)
calendar.set(Calendar.DST_OFFSET , 0);
int reCheck = calendar.get(Calendar.DST_OFFSET );
But the value is not set to 0 in recheck. I am getting the wrong
month value by using this also.
Please some one help me where I am wrong? or is this the error in
emulator ??
Thanks,
Nishant Kumar
Engineering Student
Calandar's months are from 0 to 11
You need to add 1 to the month Caladar is giving you.
I know, this is strange.
Try new Date(timeInResult);

Categories

Resources