I am new to Android and trying to practice by making small codes.
I am trying to get difference in dates and show text views based on it.
But I am gettting different difference on same day on my Android Phone.
like when I open app, it says difference in days is 5.
I close it, re open it, now it says diff is 4 !
On emulator it is working fine.
I am using following code.
Can anyone pls suggest some improvement ?
package com.practice.tablet;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class TabletsSchedule extends Activity {
public TextView tvToday;
public TextView tvMedStartDate;
public TextView tvMessage;
public TextView tvDiffInDays;
public static final String LOGGER = "ADITYA";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvToday=(TextView)findViewById(R.id.TextView01);
tvMedStartDate=(TextView)findViewById(R.id.TextView001);
tvMessage=(TextView)findViewById(R.id.TextView05);
tvDiffInDays=(TextView)findViewById(R.id.TextView06);
String[] months = {"January", "February",
"March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
Calendar today = Calendar.getInstance();
int day= today.get(Calendar.DAY_OF_MONTH);
int month=today.get(Calendar.MONTH);
int year=today.get(Calendar.YEAR);
String strMonth = months[month];
Log.d(LOGGER, "displaying today");
tvToday.setText("Today is "+day+" "+strMonth+" "+year);
Calendar medStartDate = Calendar.getInstance();
//DOB.set(year, monthOfYear+1, dayOfMonth);
medStartDate.set(Calendar.DAY_OF_MONTH, 27);
medStartDate.set(Calendar.MONTH,10);
medStartDate.set(Calendar.YEAR,2011);
int day1= medStartDate.get(Calendar.DAY_OF_MONTH);
int month1=medStartDate.get(Calendar.MONTH);
int year1=medStartDate.get(Calendar.YEAR);
String strMonth1 = months[month1];
//String med = medStartDate.toString().toString();
tvMedStartDate.setText("Medicine Start Date is "+day1+" "+strMonth1+" "+year1);
long diff = today.getTimeInMillis() - medStartDate.getTimeInMillis();
long days = diff / (24 * 60 * 60 * 1000);
tvDiffInDays.setText("Difference in days is "+days);
Log.d(LOGGER, "days is "+days);
if (days%2!=0){
tvMessage.setText("Today you have to take two tablets");
}
if (days%2==0){
tvMessage.setText("Today you have to take one tablet");
}
}
}
Use this:
Also you should store important values of
todayobject somewhere(Ex.day,month,year etc.) and also should clear it likewise. after that,you can put those values back and then finally you can use it to compare withmedStartDate.it will avoid the problem you are getting because of tiny different of time.