MMG92
MMG92

Reputation: 27

Saving variables to shared preferences

Ok so I have a variable called mHints. When my app first launches this variable has a value of 5.

I then click a button which decreases the value by 1. This works fine however when I leave my activity and load a new instance of the activity my hints reset to 5.

I have two methods which I call in my activity;

one in the on create method called loadData(); Which I believe should load the value of the hints from shared preferences.

and

one every time i click the button called saveData(); Which I believe should save the new value of the variable mHints.

To summarise I want my app to load the first time with five hints then save every time a hint is used and then load the correct value from shared preferences when a new instance of the activity is loaded. my code can be seen below.

public class MainActivity extends Activity {

// amount of Hints available
int mHints = 5;

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


    //load game data
    loadData();

    TextView NumHintstextView = (TextView) this.findViewById(R.id.NumHintstextView);
    NumHintstextView.setText(String.valueOf(mHints));
}

public void onHintsButtonClicked(View arg0) {// button to decrease hints
    Log.d(TAG, "Hints button clicked.");
    if (mHints == 0){
        alert("Oh, no! You are out of Hints! Try buying some!");
    }

    else {

        --mHints;
        saveData();
        TextView NumHintstextView = (TextView) this.findViewById(R.id.NumHintstextView);
        NumHintstextView.setText(String.valueOf(mHints));
 }

void saveData() {// save to shared preferences
    SharedPreferences.Editor spe = getPreferences(MODE_PRIVATE).edit();
    spe.putInt("hints", mHints);
    spe.commit();
    Log.d(TAG, "Saved data: Hints saved = " + String.valueOf(mHints));
}

void loadData() { // load from shared preferences
    SharedPreferences sp = getPreferences(MODE_PRIVATE);
    int mHints = sp.getInt("hints", 5000);
    Log.d(TAG, "Loaded data: Hints = " + String.valueOf(mHints));
}

Upvotes: 0

Views: 1753

Answers (2)

Byron
Byron

Reputation: 1313

You have declared a local variable in loadData method with the same name as your global varibale mHints, change your loadData method to:

void loadData() { // load from shared preferences
    SharedPreferences sp = getPreferences(MODE_PRIVATE);
    mHints = sp.getInt("hints", 5000); //Change this
    Log.d(TAG, "Loaded data: Hints = " + String.valueOf(mHints));
}

Upvotes: 1

cgogolin
cgogolin

Reputation: 1000

loadData() sets the local variable int mHints instead of the member variable mHints. Try this:

void loadData() { // load from shared preferences
    SharedPreferences sp = getPreferences(MODE_PRIVATE);
    mHints = sp.getInt("hints", 5000);
    Log.d(TAG, "Loaded data: Hints = " + String.valueOf(mHints));
}

Upvotes: 0

Related Questions