Having problems with changing SharedPreferences value

I want to save a value (“Coins”), and I’m using the SharedPreferences option (I want that the number of coins will be saved even after closing the app). I used 2 functions, one to insert (/change) the coins number, and another one to get it. In addition, I made a button which after clicking on it, it changes the number of the coins. The problem is, that the button doesn’t change it. Any help? Thanks in advance.

package com.myfirstapplication.owner.appversion1;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button btnPlay;

public void changeCoinsNumber(String key, int value) {
    SharedPreferences sharedPreferences = getSharedPreferences("PlayerInfo", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(key, value);
    editor.commit();
}

public int loadCoinsNumber(String key) {
    SharedPreferences sharedPreferences = getSharedPreferences("PlayerInfo", Activity.MODE_PRIVATE);
    int savedValue = sharedPreferences.getInt(key, 0);
    return savedValue;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    changeCoinsNumber("CoinsNumber", 5);

    TextView txt = (TextView) findViewById(R.id.spText);
    txt.setText(""+loadCoinsNumber("CoinsNumber")); // displaying the number of coins

    btnPlay = (Button) findViewById(R.id.btnPlay);
    btnPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            changeCoinsNumber("CoinsNumber", 111);
        }
    });
}

}

Answer

You need to display it again if you change the coins value as per you code. I am updating a small portion of your code.

    final TextView txt = (TextView) findViewById(R.id.spText);//Make txt final
    txt.setText(""+loadCoinsNumber("CoinsNumber")); // displaying the number of coins

    btnPlay = (Button) findViewById(R.id.btnPlay);
    btnPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            changeCoinsNumber("CoinsNumber", 111);
            txt.setText(""+loadCoinsNumber("CoinsNumber"));//Adding this line to update
        }
    });

Hope it will help you 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *