Reset An integer value at a specific time of the day

I currently have a snippet with multiple buttons and it contains onClickListener. Each time one of these buttons is pressed, the counter variable is incremented by 1 and set as text for the TextView in another fragment using SharedPreferences.

The counter will remain unchanged even after the application is completely closed and appears in subsequent launches of the application.

My new goal is to reset the counters back to 0 at the end of each day (more precisely, 23:59:00).

I decided to avoid a Google search to figure this out, and found the TimerTask, Calendar, Timer, and Date API applications in the Android developer docs; I tried to get this to work with these APIs. Unfortunately, it does not work as I planned. The variables are set to 0, but they remain at zero and will only increase to 1 and return to 0 each time you exit the application.

Is there a better way to approach this? Or is my method enough and I just need to configure / change part of the code?

One of the problems may be that I also change the reference to the counter variable (and if so, where to change it)?

Here is what I tried:

Firstfragment

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflating the layout View v = inflater.inflate(R.layout.starting_fragment, container, false); //Instantiate new Timer Timer timer = new Timer(); // Creates a Calendar object that specifies a specific time of day Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.set(Calendar.HOUR_OF_DAY, 20); cal.set(Calendar.MINUTE, 57); cal.set(Calendar.SECOND, 00); cal.set(Calendar.MILLISECOND, 00); // Instantiate a day object and use the time of day from cal object as its data Date date = cal.getTime(); TimerTask tt = new TimerTask() { // Sets the counter variables back to 0 @Override public void run() { COUNT_OOL = 0; COUNT_WTE = 0; COUNT_BLO = 0; COUNT_BLK = 0; COUNT_HBL = 0; COUNT_GRN = 0; COUNT_MTE = 0; } }; // Resets the counter variables (to 0) at the time specified by the date object timer.schedule(tt, date); // Stores count for each button back into their respective count variable // Initializes the value from previous runs of app to subsequent runs of app // This way, count variables will never get set back to 0 after onDestroy() COUNT_OOL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("oolongCount", 0); COUNT_WTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("whiteCount", 0); COUNT_BLO = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("bloomingCount", 0); COUNT_BLK = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("blackCount", 0); COUNT_HBL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("herbalCount", 0); COUNT_GRN = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("greenCount", 0); COUNT_MTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("mateCount", 0); 

OnClick method that increments counting variables:

  @Override public void onClick(View view) { int id = view.getId(); /* * Use the View interface with OnClickListener to get the Button ID's * Then you can run a switch on the Buttons (because normally switches * cannot be run on buttons */ if (id == R.id.tea_type1) { Builder oolongBuilder = new AlertDialog.Builder(StartingFragment.this.getActivity(), AlertDialog.THEME_HOLO_LIGHT); oolongBuilder.setPositiveButton("Hot", //Starts OolongTeaActivity for hot tea when clicked new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { Intent i = new Intent(StartingFragment.this.getActivity(), OolongTeaActivity.class); StartingFragment.this.getActivity().startActivity(i); } }); oolongBuilder.setNeutralButton("Iced", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(StartingFragment.this.getActivity(), ColdOolongTeaActivity.class); StartingFragment.this.getActivity().startActivity(i); } }); oolongBuilder.setTitle("Oolong Tea"); oolongBuilder.setMessage("How Do You Like Your Tea?"); AlertDialog oolongDialog = oolongBuilder.create(); oolongDialog.show(); COUNT_OOL++; SharedPreferences pref1 = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE); SharedPreferences.Editor editor1 = pref1.edit(); editor1.putInt("oolongCount", COUNT_OOL); editor1.commit(); } 

SecondFragment (sets counters as text for TextViews) :

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_tea_counter, container, false); oolongCounterText = (TextView) rootView.findViewById(R.id.oolong_counter_tv); SharedPreferences pref1 = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE); Integer counter1 = pref1.getInt("oolongCount", 0); String s1 = String.valueOf(counter1); oolongCounterText.setText(s1); 
+5
source share
5 answers

I would personally look at AlarmManager with Calendar to set the time. Then you release Service to do everything you need.

 Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 0); PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class),PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi); 

Replace MyService with the actual Service . When the service starts, it can: 1) Reset the number returns to 0 2) Check if the application is running to see if text fields should be updated immediately or if you wait for the user to start the application 3) stop the service

What you need to do before following this code:

Make sure the AlarmManager is right for you, a repeating alarm will not start after a reboot (thanks Jawnnypoo for clarifying this). See his comment below, in which he refers to the BroadcastReceiver , so that AlarmManager will start after reboot.

+3
source

Perhaps just save the day of the year and compare with the current day of the year.

 dayOfYear = DateFormat.format("D", new Date()) if (dayOfYear != lastResetDay) { resetCounters(); } 
+3
source
  • Just save the last time the counter was reset in the prefix.
  • When the fragment is launched for the first time:
    • it checks the last time the counters were reset and possibly resets them
    • it logs an alarm through the AlarmManager during the next midnight, which throws an intent broadcast
    • he registers the broadcast receiver.
  • When the broadcast receiver receives the intention, it resets the counters, notifies the fragment, and registers the alarm at midnight.
  • If the action is stopped, delete the broadcast receiver and cancel the alarm so that the application does not perform work that in any case will not be visible.
+2
source

Using AlarmManager for this task seems like a tedious job. Just add another variable to your SharedPreferences. Save the last time the counter was updated. (Maybe Calendar.getInstance (). GetTimeInMillis ())

So, when you open a fragment when getting the counter value, you should get the last time it was updated. Check the time saved for the current day. If it does not match, then reset the counter value.

If I missed something, let me know .. :)

+1
source

Some tips:

1.

 COUNT_OOL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("oolongCount", 0); COUNT_WTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("whiteCount", 0); COUNT_BLO = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("bloomingCount", 0); COUNT_BLK = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("blackCount", 0); COUNT_HBL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("herbalCount", 0); COUNT_GRN = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("greenCount", 0); COUNT_MTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("mateCount", 0); 

should be edited as follows

 private SharedPreferences sharedPreferences; sharedPreferences = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE); COUNT_OOL = sharedPreferences.getInt("oolongCount", 0); 

etc.

  1. Named according to specification requirements

  2. I think your problem with the code is to write more randomly, ending the first look at it, first you look, I'm writing about it now. Perhaps you should use the Android system clock.

-1
source

Source: https://habr.com/ru/post/1210779/


All Articles