1

当我点击一个选项时,我希望出现一个复选标志以表明它已被购买。我正在使用SharedPreferences并已建立所有链接;但是,当我单击返回或退出然后重新进入应用程序时,检查就消失了,我之前所做的任何事情的历史记录都消失了。如何保存数据,以便即使在应用程序关闭或我在游戏中的另一个页面时也能保留它。到目前为止,这是我的代码:

ImageView tick1;
int mYellCheck, mYellCheck1;
public static String sharedPrefs = "MyData";
SharedPreferences data;
SharedPreferences.Editor editor;
int mYellAlpha;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upgrades);
    update();
    coins = Replay.totalCoins + Replay4.totalCoins + Replay5.totalCoins
        + Replay6.totalCoins;
    data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
    tick1.setAlpha(mYellCheck);
}

public void update() {
    TextView coinScore = (TextView) findViewById(R.id.tvScore);
    coinScore.setText("You have " + coins + " coins");
    tick1 = (ImageView) findViewById(R.id.ivtick1);
    ImageView moreYellow = (ImageView) findViewById(R.id.ivMoreYellow);
    ImageView back = (ImageView) findViewById (R.id.ivBack);
    back.setOnClickListener(this);
    moreYellow.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.ivMoreYellow:
        mYellAlpha = 255;
        SharedPreferences.Editor editor = data.edit();
        editor.putInt("MoreYellowUpgrade", mYellAlpha);
        editor.commit();
        data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
        mYellCheck = data.getInt("MoreYellowUpgrade", 0);
        tick1.setAlpha(mYellCheck);
        break;
    case R.id.ivBack:
        Intent i = new Intent ("m.k.zaman.SpotActivity");
        startActivity(i);
        break;
    }
}

编辑

还是我应该只使用内部存储?

4

1 回答 1

0

尝试将您当前对 R.id.ivMoreYellow 的 onClick 调用替换为:

case R.id.ivMoreYellow:
    mYellAlpha = 255;
    mYellCheck = data.getInt("MoreYellowUpgrade", 0);
    tick1.setAlpha(mYellCheck);
    SharedPreferences.Editor editor = data.edit();
    editor.putInt("MoreYellowUpgrade", mYellAlpha);
    editor.commit();
    break;

You were first overwriting all of the data in the SharedPreferences, and then calling to receive that data that you just overwrote, so I placed the getInt() call before the putInt(). Do you change mYellAplha to anything other than 255 though? If you don't you will never notice a change in SharedPreferences if you are always saving and getting 255.

于 2012-07-23T04:41:48.577 回答