将变量保存到共享首选项

时间:2014-04-11 14:18:25

标签: android sharedpreferences

好的,我有一个名为mHints的变量。当我的应用首次启动时,此变量的值为5.

然后我单击一个按钮,将值减小1.这样可以正常工作,但是当我离开活动并加载活动的新实例时,我的提示重置为5。

我在我的活动中有两种方法;

一个名为loadData()的on create方法; 我认为应该从共享偏好中加载提示的值。

每次单击名为saveData()的按钮时,只有一个; 我认为应该保存变量mHints的新值。

总结一下,我希望我的应用程序第一次加载五个提示,然后在每次使用提示时保存,然后在加载活动的新实例时从共享首选项加载正确的值。我的代码可以在下面看到。

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));
}

2 个答案:

答案 0 :(得分:1)

您已在loadData方法中声明了一个与全局变量mHints同名的本地变量,将您的loadData方法更改为:

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));
}

答案 1 :(得分:0)

loadData()设置局部变量int mHints而不是成员变量mHints。试试这个:

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));
}