public long getDays(){
Date today = new Date ( );
Calendar cal = Calendar.getInstance (TimeZone.getTimeZone("GMT"));
// Set as today
cal.setTime ( today );
System.out.println ( "Today Cal: "+cal.get ( Calendar.YEAR ) + "Y / " + ( cal.get ( Calendar.MONTH ) + 1 ) + "M / " + cal.get ( Calendar.DATE ) + " D" );
Calendar cal2 = Calendar.getInstance (TimeZone.getTimeZone("GMT") );
//Month has offset -1. June = 5
cal2.set ( 2011, 5, 15 );//YY MM DD
System.out.println ( "Start Day Cal2: "+cal2.get ( Calendar.YEAR ) + "Y / " + ( cal2.get ( Calendar.MONTH ) + 1 ) + "M / " + cal2.get ( Calendar.DATE ) + " D" );
long count = 0;
while ( !cal2.after ( cal ) ) {
count++;
//increment date
cal2.add ( Calendar.DATE, 1 );
}
System.out.println ( "Ending Cal2: "+cal2.get ( Calendar.YEAR ) + "Y / " + ( cal2.get ( Calendar.MONTH ) + 1 ) + "M / " + cal2.get ( Calendar.DATE ) + " D" );
return count;
}
This is the code that I am using to calculate the difference in Days between today and 2011 June 15th.
This always works on Eclipse IDE, but when I implement this on Android, it shows 2 different results by random chance.
Most of the times it shows 2405, but sometimes it shows 2406 (Although the date should not have changed as it is 3 AM in the UK now.)
This is what is shown on System.out.println. It has the same start date and end date, but by a random chance, while loop counts 1 extra. How?
It only happens on Android. This is the code showing how the textview is being updated as a widget if it helps.
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int count = appWidgetIds.length;
//Set Date Text
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.haruhi_widget);
long days=getDays();
remoteViews.setTextViewText(R.id.textView, days+context.getString(R.string.days));
//Set ImageView
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.haruhi1,options);
remoteViews.setImageViewBitmap(R.id.imageView,bitmap);
Intent intent = new Intent(context, HaruhiWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
remoteViews.setOnClickPendingIntent(R.id.imageView, getPendingSelfIntent(context, KYON_KUN_DENWA));
for (int i = 0; i < count; i++) {
// System.out.println(count+"appWidgetIds[i]");
int widgetId = appWidgetIds[i];
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}