0

I am trying to increase my shared preferences at midnight every day by one and retrieve it when user open app in a day .but here are two problems, 1,number is increasing but it goes back to decrement after hour. 2, it increases one time while I want enter code hereto increase by one every day.` here is my code

public class MainActivity extends AppCompatActivity {
    WebView wv;
    int i=1;

    SharedPreferences sp;
    Calendar currentTime = Calendar.getInstance();
    int hour = currentTime.get(Calendar.HOUR_OF_DAY);
    String link = "https://www.google.com/";

    ...

    Button btn;wv=(WebView)findViewById(R.id.wv);
    btn=(Button)findViewById(R.id.btn);
    sp=getSharedPreferences("page",MODE_PRIVATE);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences.Editor editor=sp.edit();
            editor.putInt("ch",i);
            editor.commit();
        }
    });

    int ret=(sp.getInt("ch",1));

    if(hour==00) {
        ret++;
    }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
m bilal
  • 11
  • 4
  • 1
    Have you considered saving a starting date once to `SharedPreferences`, and then just calculating the number of days since, whenever it's needed? Seems simpler than trying to update `SharedPreferences` every day. – Mike M. Sep 30 '18 at 02:18
  • Yeah I think this would be the best approach instead of creating a service daily. Fetch the current date on the very first run of that device, and store the same to sharedpreference, and then onwards whenever required just substract the same from the current date in order to display that in your view – Anirban Roy Sep 30 '18 at 07:02

2 Answers2

0

You're never changing the value of i, so editor.putInt("ch",i); will always reset it to 1 within the SharedPreferences.

Might want to see Running task periodicaly(once a day/once a week)

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

You can not increment shared prefrence value like this , if you want to increment your sharedprefrence value everyday 00:00 then you need to run a background job scheduler that keeps running in background even if the app is killed and as the clock ticks 00:00 it will increment the value by 1 and next time the user opens the app will find the updated value everytime.

Ravi
  • 912
  • 1
  • 12
  • 17