onrkr123
onrkr123

Reputation: 23

How to contunie count from sharedpreferences number in counter app

I need your help. I'm trying to create an app but I can't fix a little problem. In my counter app I added sharedpreferences to get a value preserved after the app is closed and restore the value as the app gets opened. But I want to continue to count starting from the number at previous exit. The number is saved, but app starts counting from 0 again when I click the button. Here's my code:

public class MainActivity extends AppCompatActivity {

    TextView showValue;
    int counter,storedNumber;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);    
        showValue = (TextView) findViewById(R.id.counterValue);    
        sharedPreferences = this.getSharedPreferences("com.example.pc.zikir", Context.MODE_PRIVATE);    
        int storedNumber = sharedPreferences.getInt("storedNumber",0);    
        showValue.setText(Integer.toString(storedNumber));    
    }


    public void countIN(View view) {    
        showValue.setText(Integer.toString(counter));    
        sharedPreferences.edit().putInt("storedNumber",counter).apply();    
        counter++;
    }

    public void resetCount (View view) {
        counter = 0;
        showValue.setText(String.valueOf(counter));
    }

    public void hadisButton(View view){
        Intent intent = new Intent(MainActivity.this,Main2Activity.class);
        startActivity(intent);
    }
}

Upvotes: 2

Views: 49

Answers (1)

Michel_T.
Michel_T.

Reputation: 2821

I don't see that you assigned the saved value back to the counter value. I suppose it should be something like that:

int storedNumber = sharedPreferences.getInt("storedNumber",0);    
showValue.setText(Integer.toString(storedNumber));
counter = storedNumber;

in your onCreate() method.

And I don't see any reason why you need the storedNumber variable at all - I'd saved/restored the counter variable.

Upvotes: 2

Related Questions