TextView timer seconds digits jumping - java

I have this code which simply displays a countdown clock to an event. I am having an issue with it with regards to the last seconds place jumping digits unlike a normal clock. Here is the code I am working with. Could someone please offer some guidance to where this issue may be. Kind regards.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Timer().schedule(new TimerTask() {
File sdcard = Environment.getExternalStorageDirectory();
File cfgFile = new File(sdcard, "TimeTillParis/config.txt");
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
try {
InputStream is = new FileInputStream(cfgFile);
Properties prop = new Properties();
prop.load(is);
int mmY = Integer.parseInt(prop.getProperty("YEAR"));
int mmM = Integer.parseInt(prop.getProperty("MONTH"));
int mmD = Integer.parseInt(prop.getProperty("DAY"));
int mmH = Integer.parseInt(prop.getProperty("HOUR"));
int mmC = Integer.parseInt(prop.getProperty("MINUTE"));
int mmS = Integer.parseInt(prop.getProperty("SECOND"));
Calendar cal = Calendar.getInstance();
Date today = new Date(System.currentTimeMillis());
cal.set(Calendar.YEAR, mmY);
cal.set(Calendar.MONTH, mmM);
cal.set(Calendar.DAY_OF_MONTH, mmD);
cal.set(Calendar.HOUR_OF_DAY, mmH);
cal.set(Calendar.MINUTE, mmC);
cal.set(Calendar.SECOND, mmS);
long milliseconds = (cal.getTimeInMillis() - today.getTime());
String mD="", mH="", mM="", mS="", boxText="";
mD += (milliseconds / (1000*60*60*24));
mH += (milliseconds / (1000*60*60) % 24);
mM += (milliseconds / (1000*60) % 60);
mS += (milliseconds / 1000 % 60);
boxText += "Next visit to Paris in \n\n" +
mD + "d " +
mH + "h " +
mM + "m " +
mS + "s";
TextView textView = (TextView) findViewById(R.id.textView_date_display);
textView.setText(boxText);
} catch (FileNotFoundException e) {
String cfgNotFound="";
cfgNotFound += "config.txt not found!";
TextView textView = (TextView) findViewById(R.id.textView_date_display);
textView.setText(cfgNotFound);
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}, 0, 100);
}
}

I prepared complete solution, let me know if you have some questions:
public class MainActivity extends Activity {
private static final int COUNTDOWN_INTERVAL = 1000;
MyTimer timer;
Calendar eventTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File sdcard = Environment.getExternalStorageDirectory();
File cfgFile = new File(sdcard, "TimeTillParis/config.txt");
try {
InputStream is = new FileInputStream(cfgFile);
Properties prop = new Properties();
prop.load(is);
int mmY = Integer.parseInt(prop.getProperty("YEAR"));
int mmM = Integer.parseInt(prop.getProperty("MONTH"));
int mmD = Integer.parseInt(prop.getProperty("DAY"));
int mmH = Integer.parseInt(prop.getProperty("HOUR"));
int mmC = Integer.parseInt(prop.getProperty("MINUTE"));
int mmS = Integer.parseInt(prop.getProperty("SECOND"));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, mmY);
cal.set(Calendar.MONTH, mmM);
cal.set(Calendar.DAY_OF_MONTH, mmD);
cal.set(Calendar.HOUR_OF_DAY, mmH);
cal.set(Calendar.MINUTE, mmC);
cal.set(Calendar.SECOND, mmS);
eventTime = cal;
} catch (FileNotFoundException e) {
String cfgNotFound="";
cfgNotFound += "config.txt not found!";
TextView textView = (TextView) findViewById(R.id.textView_date_display);
textView.setText(cfgNotFound);
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
if(eventTime != null) {
long millisInFuture = (eventTime.getTimeInMillis() - System.currentTimeMillis());
timer = new MyTimer(this, millisInFuture, COUNTDOWN_INTERVAL);
timer.start();
}
}
#Override
protected void onPause() {
super.onPause();
if(timer != null) {
timer.cancel();
}
}
private static class MyTimer extends CountDownTimer {
TextView textView;
public MyTimer(Activity actitivy, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// findViewById is very expansive, so fined it only once
textView = (TextView) actitivy.findViewById(R.id.textView_date_display);
}
#Override
public void onFinish() {
}
#Override
public void onTick(long millisUntilFinished) {
SimpleDateFormat sdf = new SimpleDateFormat("'Next visit to Paris in \n\n'd'd 'h'h 'm'm 's's'");
String boxText = sdf.format(new Date(millisUntilFinished));
textView.setText(boxText);
}
}
}

Related

inserting Start, Stop and differenece time into sql database an android studio java language

I have wrote a code when I click on button start it show current time and turn text into stop then I click on stop it show me stop current time and calculate difference. after that I made a class to insert all these three start stop and difference into SQL database.
my problem is when I click on stop button it show me toast time added but value not added into database it show blank column into database. my database table column shows no values.
public class cleaning extends Fragment {
TextView tvstarttime;
Button btn_start;
Button btn_end;
TextView tvend;
TextView diffence;
boolean isStarted = false;
String starttime, endtime, timedifference;
ProgressDialog progressDialog;
Connection conn;
boolean isSucess = false;
NetworkManager networkManager = new NetworkManager();
SharedPrefManager sharedPrefManager = new SharedPrefManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_cleaning, container, false);
tvstarttime = view.findViewById(R.id.txtstarttime);
btn_start = view.findViewById(R.id.btn_start);
tvend = view.findViewById(R.id.txtendtime);
uploadcart uploadcart = new uploadcart();
uploadcart.execute();
diffence=view.findViewById(R.id.txtdifference);
starttime = tvstarttime.getText().toString().trim();
endtime = tvend.getText().toString().trim();
timedifference = diffence.getText().toString().trim();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isStarted){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time = format.format(calendar.getTime());
tvend.setText(time);
try {
Date date1 = format.parse(tvend.getText().toString());
Date date2 = format.parse(tvstarttime.getText().toString());
long mills = date1.getTime() - date2.getTime();
Log.v("Data1", ""+date1.getTime());
Log.v("Data2", ""+date2.getTime());
int hours = (int) (mills/(1000 * 60 * 60));
int mins = (int) (mills % (1000*60*60));
String diff = hours + ":" + mins;
diffence.setText(diff);
} catch (ParseException e) {
e.printStackTrace();
}
btn_start.setText("START");
}else {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time1 = format.format(calendar.getTime());
tvstarttime.setText(time1);
btn_start.setText("STOP");
}
isStarted = !isStarted;
}
});
return view;
}
private class uploadcart extends AsyncTask<Void, Void, Void> {
/* #Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(ProductDetailFragment.this);
progressDialog.setTitle("Creating account please wait!");
progressDialog.show();
super.onPreExecute();
}*/
#Override
protected Void doInBackground(Void... voids) {
try {
ConnectionHelper con = new ConnectionHelper();
conn = con.connectionclasss(Const.DBUserNameStr, Const.DBPasswordStr, Const.db, Const.ip);
String queryStmt = "Insert into CleaningTable" +
" (StartTime, StopTime, TimeTaken) values "
+ "('"
+ starttime
+ "','"
+ endtime
+ "','"
+ timedifference
+ "')";
Statement stmt = conn.createStatement();
isSucess = stmt.execute(queryStmt);
isSucess = true;
conn.close();
// return data;
} catch (Exception e) {
isSucess = false;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (isSucess) {
Toast.makeText(getActivity(), "time added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "time not added", Toast.LENGTH_SHORT).show();
}
super.onPostExecute(aVoid);
}
}
}

inserting value into SQL database using java language in adroid studio

i have a code that take start time and stop time by clicking on button and make the difference between two time.
i want to issert this start, stop and difference value into database. But my code didnot insert these value into database. it insert no value. my code is not giving me any error. when i run it databse rows increse but no value shows into table. all column shows empty.
please help me friends.
public class cleaning extends Fragment {
TextView tvstarttime;
Button btn_start;
Button btn_end;
TextView tvend;
TextView diffence;
boolean isStarted = false;
String starttime, endtime, timedifference;
ProgressDialog progressDialog;
Connection conn;
boolean isSucess = false;
NetworkManager networkManager = new NetworkManager();
SharedPrefManager sharedPrefManager = new SharedPrefManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_cleaning, container, false);
tvstarttime = view.findViewById(R.id.txtstarttime);
btn_start = view.findViewById(R.id.btn_start);
tvend = view.findViewById(R.id.txtendtime);
diffence=view.findViewById(R.id.txtdifference);
starttime = tvstarttime.getText().toString().trim();
endtime = tvend.getText().toString().trim();
timedifference = diffence.getText().toString().trim();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isStarted){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time = format.format(calendar.getTime());
tvend.setText(time);
try {
Date date1 = format.parse(tvend.getText().toString());
Date date2 = format.parse(tvstarttime.getText().toString());
long mills = date1.getTime() - date2.getTime();
Log.v("Data1", ""+date1.getTime());
Log.v("Data2", ""+date2.getTime());
int hours = (int) (mills/(1000 * 60 * 60));
int mins = (int) (mills % (1000*60*60));
String diff = hours + ":" + mins;
diffence.setText(diff);
}
catch (ParseException e) {
e.printStackTrace();
}
btn_start.setText("START");
}else {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time1 = format.format(calendar.getTime());
tvstarttime.setText(time1);
btn_start.setText("STOP");
}
isStarted = !isStarted;
}
});
return view;
}
private class uploadcart extends AsyncTask<Void, Void, Void> {
/* #Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(ProductDetailFragment.this);
progressDialog.setTitle("Creating account please wait!");
progressDialog.show();
super.onPreExecute();
}*/
#Override
protected Void doInBackground(Void... voids) {
try {
ConnectionHelper con = new ConnectionHelper();
conn = con.connectionclasss(Const.DBUserNameStr, Const.DBPasswordStr, Const.db, Const.ip);
String queryStmt = "Insert into CleaningTable" +
" (StartTime, StopTime, TimeTaken) values "
+ "('"
+ starttime
+ "','"
+ endtime
+ "','"
+ timedifference
+ "')";
Statement stmt = conn.createStatement();
isSucess = stmt.execute(queryStmt);
isSucess = true;
conn.close();
// return data;
} catch (Exception e) {
isSucess = false;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (isSucess) {
Toast.makeText(getActivity(), "time added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "time not added", Toast.LENGTH_SHORT).show();
}
super.onPostExecute(aVoid);
}
}
}

how to compare date and not display feauter week date in android

public class TestActvity extends AppCompatActivity implements View.OnClickListener {
Button next;
Button previous;
TextView textView;
int interval = 2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
next = (Button) findViewById(R.id.next);
previous = (Button) findViewById(R.id.previous);
next.setOnClickListener(this);
previous.setOnClickListener(this);
textView = (TextView) findViewById(R.id.textView);
getDate(interval);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.next)
{
interval = interval + 7;
getDate(interval);
} else if (view.getId() == R.id.previous) {
interval = interval - 7;
getDate(interval);
}
}
public void getDate(int interval) {
try {
Calendar c = GregorianCalendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.add(Calendar.DAY_OF_WEEK, interval - 2);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());
textView.setText(startDate + " to " + endDate);
Date date = new Date();
String modifiedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
if ( endDate.compareTo(modifiedDate) > 0) {
Log.d("data", "" + "");
}
Log.d("data", "" + "");
} catch (Exception e) {
}
}
}
Using this code, i am displaying Monday to Sunday like
2017-7-3 to 2017-7-9 ,2017-7-10 to 2017-7-16 ,2017-7-17 to 2017-7-23
,2017-7-24 to 2017-7-30 ,2017-7-31 to 2017-8-5 ...
Receptively but what I want, if current week is
2017-7-24 to 2017-7-30
then when we click on next week it should display it should display only previous week please suggest me in this scenario I will compare date.
if (c.getTime().after(new Date())){
next.setVisibility(View.GONE);
}else {
next.setVisibility(View.VISIBLE);
}
apply this Condition and enjoy !!

Calendar cannot initialize null pointer exception on 5.1 API level

This time reminder class, time reminder is crashing on click and erroe goes on "custom.showDialogue" and the error is the following:
FATAL EXCEPTION: main
Process: com.appmetrik.notestakingapp, PID: 18607
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.app.notes.CustomDateTimePicker.showDialog()' on a null object reference
at com.app.notes.AddReminder.onClick(AddReminder.java:261)
public class AddReminder extends AppCompatActivity implements
android.view.View.OnClickListener`{
CustomDateTimePicker custom = null;
TextView txt_Time;
TextView txt_Date;
TextView txt_Day;
EditText et_Reminder_Title;
EditText et_Reminder_Description;
ImageButton btn_Submit_Reminder;
public static String var_Reminder_Title;
public String var_Reminder_Description;
public String var_Reminder_Time;
public String var_Reminder_Date;
public String var_Reminder_Day;
public int var_Not_Day;
public int var_Not_Month;
public int var_Not_Year;
public int var_Not_Hour;
public int var_Not_Min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_reminder);
txt_Time = (TextView) findViewById(R.id.txtEditTime);
txt_Time.setOnClickListener(this);
txt_Date = (TextView) findViewById(R.id.txtEditDate);
txt_Date.setOnClickListener(this);
txt_Day = (TextView) findViewById(R.id.txtEditDay);
txt_Day.setOnClickListener(this);
et_Reminder_Title= (EditText) findViewById(R.id.etEditReminderTitle);
et_Reminder_Description = (EditText) findViewById(R.id.etReminderDescription);
btn_Submit_Reminder = (ImageButton) findViewById(R.id.imgBtnSubmitReminder);
btn_Submit_Reminder.setOnClickListener(this);
try {
custom = new CustomDateTimePicker(AddReminder.this,
new CustomDateTimePicker.ICustomDateTimeListener() {
#Override
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName,
int hour24, int hour12, int min, int sec,
String AM_PM) {
txt_Time.setText(hour12 + ":" + min + " " + AM_PM);
txt_Date.setText(calendarSelected
.get(Calendar.DAY_OF_MONTH)
+ "/" + (monthNumber + 1) + "/" + year);
txt_Day.setText(weekDayFullName);
var_Not_Hour = hour24;
var_Not_Min = min;
var_Not_Month = monthNumber;
var_Not_Day = calendarSelected
.get(Calendar.DAY_OF_MONTH);
var_Not_Year = year;
}
#Override
public void onCancel() {
}
});
/**
* Pass Directly current time format it will return AM and PM if you set
* false
*/
custom.set24HourFormat(false);
/**
* Pass Directly current data and time to show when ita pop up
*/
custom.setDate(Calendar.getInstance());
}
catch (Exception ex){
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Calendar Initialization Failed...", Toast.LENGTH_LONG).show();
}
findViewById(R.id.button_date).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
custom.showDialog();
}
});
}
public void getValues(){
var_Reminder_Title = et_Reminder_Title.getText().toString();
var_Reminder_Time = txt_Time.getText().toString();
var_Reminder_Date = txt_Date.getText().toString();
var_Reminder_Day = txt_Day.getText().toString();
var_Reminder_Description = et_Reminder_Description.getText().toString();
}
public boolean validate()
{
boolean allValid = true;
if(et_Reminder_Title.getText().toString().trim().length() == 0)
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
et_Reminder_Title.setError("Please Enter a Reminder Title here");
}
});
}
if(txt_Time.getText() == "Time")
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
et_Reminder_Title.setError("Tap Here to Select a Due Date and Time");
}
});
}
return allValid;
}
public void addReminder(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS reminders(ReminderId INTEGER PRIMARY KEY AUTOINCREMENT, ReminderTitle Text,ReminderTime Text,ReminderDate Text,ReminderDay Text, ReminderDescription Text);");
db.execSQL("INSERT INTO reminders(ReminderTitle,ReminderTime,ReminderDate,ReminderDay,ReminderDescription) VALUES('"+var_Reminder_Title+"','"+var_Reminder_Time+"','"+var_Reminder_Date+"','"+var_Reminder_Day+"','"+var_Reminder_Description+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Reminder Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Reminder Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void addNotification(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS notifications(NotificationId INTEGER PRIMARY KEY AUTOINCREMENT, NotificationTitle Text);");
db.execSQL("INSERT INTO notifications(NotificationTitle) VALUES('"+var_Reminder_Title+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Notification Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Notification Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void remind(){
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// set for 30 seconds later
alarmMgr.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + 30000, alarmIntent);
Toast.makeText(AddReminder.this, "Set Alarm", Toast.LENGTH_LONG).show();
}
public void al(){
// for Alarm 25/12/2012 at 12.00
Calendar myAlarmDate = Calendar.getInstance();
myAlarmDate.setTimeInMillis(System.currentTimeMillis());
myAlarmDate.set(var_Not_Year, var_Not_Month, var_Not_Day, var_Not_Hour, var_Not_Min, 0);
//Toast.makeText(AddReminder.this, ""+var_Not_Year+" "+ var_Not_Month+" "+ var_Not_Day+" "+var_Not_Hour+" "+var_Not_Min+" "+ 0, Toast.LENGTH_LONG).show();
//Create alarm manager
AlarmManager alarmMgr0 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Create pending intent & register it to your alarm notifier class
Intent intent0 = new Intent(this, AlarmReceiver.class);
//intent0.putExtra("Ringtone",getResources().getResourceName(R.raw.bbm_tone));
intent0.putExtra("Heading",var_Reminder_Title);
PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, intent0, 0);
//set timer you want alarm to work (here I have set it to 7.20pm)
//Intent intent0 = new Intent(this, OldEntryRemover.class);
/* Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.MONTH,12);
timeOff9.set(Calendar.DAY_OF_MONTH,1);
timeOff9.set(Calendar.YEAR,2015);
timeOff9.set(Calendar.HOUR_OF_DAY, 16);
timeOff9.set(Calendar.MINUTE, 45);
timeOff9.set(Calendar.SECOND, 0);
*/
//set that timer as a RTC Wakeup to alarm manager object
alarmMgr0.set(AlarmManager.RTC_WAKEUP, myAlarmDate.getTimeInMillis(), pendingIntent0);
// Toast.makeText(AddReminder.this, "Alarm", Toast.LENGTH_LONG).show();
}
#Override
public void onBackPressed ()
{
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.txtEditTime || v.getId() == R.id.txtEditDate || v.getId() == R.id.txtEditDay){
// custom.showDialog();
}
else if(v.getId() == R.id.imgBtnSubmitReminder) {
if (validate() == true) {
getValues();
addReminder();
// addNotification();
al();
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
}
}
}
this is custom date time picker class which is having the method showDialogue and it is using in the previous class. It is working perfectly on the version is less than 5.0 API but it is crashing on the version of 5.1 error is datetimepicker cannot be initialized.
public class CustomDateTimePicker implements android.view.View.OnClickListener {
private DatePicker datePicker;
private TimePicker timePicker;
private ViewSwitcher viewSwitcher;
private final int SET_DATE = 100, SET_TIME = 101, SET = 102, CANCEL = 103;
private Button btn_setDate, btn_setTime, btn_set, btn_cancel;
private Calendar calendar_date = null;
private Activity activity;
private ICustomDateTimeListener iCustomDateTimeListener = null;
private Dialog dialog;
private boolean is24HourView = true, isAutoDismiss = true;
private int selectedHour, selectedMinute;
public CustomDateTimePicker(Activity a,
ICustomDateTimeListener customDateTimeListener) {
activity = a;
iCustomDateTimeListener = customDateTimeListener;
dialog = new Dialog(activity);
// Context context = new ContextThemeWrapper(new MyContextWrapper, android.R.style.Theme_Holo_Light_Dialog);
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});
/*
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});*/
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View dialogView = getDateTimePickerLayout();
dialog.setContentView(dialogView);
}
public View getDateTimePickerLayout() {
LinearLayout.LayoutParams linear_match_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout.LayoutParams linear_wrap_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams frame_match_wrap = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
LinearLayout linear_main = new LinearLayout(activity);
linear_main.setLayoutParams(linear_match_wrap);
linear_main.setOrientation(LinearLayout.VERTICAL);
linear_main.setGravity(Gravity.CENTER);
LinearLayout linear_child = new LinearLayout(activity);
linear_child.setLayoutParams(linear_wrap_wrap);
linear_child.setOrientation(LinearLayout.VERTICAL);
LinearLayout linear_top = new LinearLayout(activity);
linear_top.setLayoutParams(linear_match_wrap);
btn_setDate = new Button(activity);
btn_setDate.setLayoutParams(button_params);
btn_setDate.setText("Set Date");
btn_setDate.setId(SET_DATE);
btn_setDate.setOnClickListener(this);
btn_setTime = new Button(activity);
btn_setTime.setLayoutParams(button_params);
btn_setTime.setText("Set Time");
btn_setTime.setId(SET_TIME);
btn_setTime.setOnClickListener(this);
linear_top.addView(btn_setDate);
linear_top.addView(btn_setTime);
viewSwitcher = new ViewSwitcher(activity);
viewSwitcher.setLayoutParams(frame_match_wrap);
datePicker = new DatePicker(activity);
timePicker = new TimePicker(activity);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
selectedHour = hourOfDay;
selectedMinute = minute;
}
});
viewSwitcher.addView(timePicker);
viewSwitcher.addView(datePicker);
LinearLayout linear_bottom = new LinearLayout(activity);
linear_match_wrap.topMargin = 8;
linear_bottom.setLayoutParams(linear_match_wrap);
btn_set = new Button(activity);
btn_set.setLayoutParams(button_params);
btn_set.setText("Set");
btn_set.setId(SET);
btn_set.setOnClickListener(this);
btn_cancel = new Button(activity);
btn_cancel.setLayoutParams(button_params);
btn_cancel.setText("Cancel");
btn_cancel.setId(CANCEL);
btn_cancel.setOnClickListener(this);
linear_bottom.addView(btn_set);
linear_bottom.addView(btn_cancel);
linear_child.addView(linear_top);
linear_child.addView(viewSwitcher);
linear_child.addView(linear_bottom);
linear_main.addView(linear_child);
//Invisible Calender View
datePicker.getCalendarView().setVisibility(View.GONE);
return linear_main;
}
public void showDialog() {
if (!dialog.isShowing()) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
selectedHour = calendar_date.get(Calendar.HOUR_OF_DAY);
selectedMinute = calendar_date.get(Calendar.MINUTE);
timePicker.setIs24HourView(is24HourView);
timePicker.setCurrentHour(selectedHour);
timePicker.setCurrentMinute(selectedMinute);
datePicker.updateDate(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DATE));
dialog.show();
btn_setDate.performClick();
btn_setTime.performClick();
}
}
public void setAutoDismiss(boolean isAutoDismiss) {
this.isAutoDismiss = isAutoDismiss;
}
public void dismissDialog() {
if (!dialog.isShowing())
dialog.dismiss();
}
public void setDate(Calendar calendar) {
if (calendar != null)
calendar_date = calendar;
}
public void setDate(Date date) {
if (date != null) {
calendar_date = Calendar.getInstance();
calendar_date.setTime(date);
}
}
public void setDate(int year, int month, int day) {
if (month < 12 && month >= 0 && day < 32 && day >= 0 && year > 100
&& year < 3000) {
calendar_date = Calendar.getInstance();
calendar_date.set(year, month, day);
}
}
public void setTimeIn24HourFormat(int hourIn24Format, int minute) {
if (hourIn24Format < 24 && hourIn24Format >= 0 && minute >= 0
&& minute < 60) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = true;
}
}
public void setTimeIn12HourFormat(int hourIn12Format, int minute,
boolean isAM) {
if (hourIn12Format < 13 && hourIn12Format > 0 && minute >= 0
&& minute < 60) {
if (hourIn12Format == 12)
hourIn12Format = 0;
int hourIn24Format = hourIn12Format;
if (!isAM)
hourIn24Format += 12;
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = false;
}
}
public void set24HourFormat(boolean is24HourFormat) {
is24HourView = is24HourFormat;
}
public interface ICustomDateTimeListener {
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName, int hour24,
int hour12, int min, int sec, String AM_PM);
public void onCancel();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case SET_DATE:
btn_setTime.setEnabled(true);
btn_setDate.setEnabled(false);
viewSwitcher.showNext();
break;
case SET_TIME:
btn_setTime.setEnabled(false);
btn_setDate.setEnabled(true);
viewSwitcher.showPrevious();
break;
case SET:
if (iCustomDateTimeListener != null) {
int month = datePicker.getMonth();
int year = datePicker.getYear();
int day = datePicker.getDayOfMonth();
calendar_date.set(year, month, day, selectedHour,
selectedMinute);
iCustomDateTimeListener.onSet(dialog, calendar_date,
calendar_date.getTime(), calendar_date
.get(Calendar.YEAR),
getMonthFullName(calendar_date.get(Calendar.MONTH)),
getMonthShortName(calendar_date.get(Calendar.MONTH)),
calendar_date.get(Calendar.MONTH), calendar_date
.get(Calendar.DAY_OF_MONTH),
getWeekDayFullName(calendar_date
.get(Calendar.DAY_OF_WEEK)),
getWeekDayShortName(calendar_date
.get(Calendar.DAY_OF_WEEK)), calendar_date
.get(Calendar.HOUR_OF_DAY),
getHourIn12Format(calendar_date
.get(Calendar.HOUR_OF_DAY)), calendar_date
.get(Calendar.MINUTE), calendar_date
.get(Calendar.SECOND), getAMPM(calendar_date));
}
if (dialog.isShowing() && isAutoDismiss)
dialog.dismiss();
break;
case CANCEL:
if (iCustomDateTimeListener != null)
iCustomDateTimeListener.onCancel();
if (dialog.isShowing())
dialog.dismiss();
break;
}
}
/**
* #param date
* date in String
* #param fromFormat
* format of your <b>date</b> eg: if your date is 2011-07-07
* 09:09:09 then your format will be <b>yyyy-MM-dd hh:mm:ss</b>
* #param toFormat
* format to which you want to convert your <b>date</b> eg: if
* required format is 31 July 2011 then the toFormat should be
* <b>d MMMM yyyy</b>
* #return formatted date
*/
public static String convertDate(String date, String fromFormat,
String toFormat) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
Date d = simpleDateFormat.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
simpleDateFormat = new SimpleDateFormat(toFormat);
simpleDateFormat.setCalendar(calendar);
date = simpleDateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
private String getMonthFullName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getMonthShortName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getWeekDayFullName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private String getWeekDayShortName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private int getHourIn12Format(int hour24) {
int hourIn12Format = 0;
if (hour24 == 0)
hourIn12Format = 12;
else if (hour24 <= 12)
hourIn12Format = hour24;
else
hourIn12Format = hour24 - 12;
return hourIn12Format;
}
private String getAMPM(Calendar calendar) {
String ampm = (calendar.get(Calendar.AM_PM) == (Calendar.AM)) ? "AM"
: "PM";
return ampm;
}
enter image description here
private void resetData() {
calendar_date = null;
is24HourView = true;
}
public static String pad(int integerToPad) {
if (integerToPad >= 10 || integerToPad < 0)
return String.valueOf(integerToPad);
else
return "0" + String.valueOf(integerToPad);
}
}

Countdown timer problems Android

My app checks if there is a file with a date.
If there is a date, it calculates the difference between today and that (future) date and initializes a timer counting down the seconds until that date in the way X days Y hours Z minutes S seconds.
If there is no file, then the user can select a date with a button. The program will store the date in the file and set the countdown.
There is a Delete Button to delete the date and choose another. This delete button should cancel the timer so it stops counting.
The timer does not stop when I cancel it. My timer is ticking but the difference is 2 seconds instead of one. It shows 40 38 36... instead of 40 39 38...
And lastly, it's storing the picked date twice instead of once.
The DatePicker code is from here.
public class NextVisit extends Activity implements DatePickerFragment.TheListener{
protected Vibrator vibrate;
protected int SECONDS_IN_A_DAY = 24 * 60 * 60;
protected String filePath = "";
protected SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
final long[] pattern = {0, 1000, 500, 1000, 500, 1000, 500, 1000 };
CountDownTimer timer = null;
String dateString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next_visit);
final TextView label = (TextView) findViewById(R.id.label);
final TextView countdown = (TextView) findViewById(R.id.time_visit);
final Button bDate = (Button) findViewById(R.id.date_button);
final Button bDelete = (Button) findViewById(R.id.delete_button);
File dir = new File(getFilesDir(), "loveApp");
if(!dir.exists())
dir.mkdirs();
final File f = new File(getFilesDir()+"/loveApp"+"/love_date.txt");
filePath = f.getAbsolutePath();
vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE);
bDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(f.exists()){
f.delete();
System.out.println("File deleted successfully");
bDate.setVisibility(View.VISIBLE);
label.setText(R.string.next_visit1);
timer.cancel();
countdown.setText("");
System.out.println("I cancelled the timer");
bDelete.setVisibility(View.INVISIBLE);
bDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
bDelete.setVisibility(View.VISIBLE);
bDate.setVisibility(View.INVISIBLE);
picker.show(getFragmentManager(), "datePicker");
}
});
}
}
});
if(f.exists()){
System.out.println("File exists");
bDate.setVisibility(View.INVISIBLE);
label.setText(getString(R.string.label));
try{
BufferedReader br = new BufferedReader(new FileReader(f));
dateString = br.readLine();
br.close();
System.out.println("Date: "+dateString);
Date finalDate = formatter.parse(dateString);
setCountdown(finalDate);
}catch(Exception e){
e.printStackTrace();
label.setText("ERROR");
}
}else{
System.out.println("File DOES NOT EXIST");
bDelete.setVisibility(View.INVISIBLE); //Removing the delete date button
bDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
bDelete.setVisibility(View.VISIBLE);
bDate.setVisibility(View.INVISIBLE);
picker.show(getFragmentManager(), "datePicker");
}
});
}
}
public void setCountdown(Date finishDate){
long end = finishDate.getTime();
final TextView countdown = (TextView) findViewById(R.id.time_visit);
timer = new CountDownTimer(end, 1000){
#Override
public void onTick(long millisUntilFinished) {
long now = Calendar.getInstance(Locale.GERMANY).getTimeInMillis()+1000;
long diff = millisUntilFinished - now;
long diffSec = diff / 1000;
long days = diffSec / SECONDS_IN_A_DAY;
long secondsDay = diffSec % SECONDS_IN_A_DAY;
long seconds = secondsDay % 60;
long minutes = (secondsDay / 60) % 60;
long hours = (secondsDay / 3600);
countdown.setText(days+ " days, "+ hours + "hours, "+minutes + "m, "+seconds + "s remaining!");
}
#Override
public void onFinish() {
countdown.setText("done!");
vibrate.vibrate(pattern,-1);
}
}.start();
}
#Override
public void returnDate(String date) {
dateString = date;
TextView label = (TextView) findViewById(R.id.label);
label.setText(R.string.label);
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(new File(filePath)));
bw.write(dateString);
bw.close();
System.out.println("Saved the file, date is: "+ dateString);
Date finishDate = formatter.parse(date);
setCountdown(finishDate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think problem in this string long now = Calendar.getInstance(Locale.GERMANY).getTimeInMillis()+1000; you need put it outside of countdowntimer code.
final long now = Calendar.getInstance(Locale.GERMANY).getTimeInMillis()+1000;
timer = new CountDownTimer(end, 1000){
#Override
public void onTick(long millisUntilFinished) {
long diff = millisUntilFinished - now;
long diffSec = diff / 1000;
...
};

Categories