使用SharedPreferences来保存数据时遇到问题

时间:2016-09-29 16:58:51

标签: java android sharedpreferences

我试图通过SharedPreferences接口保存swipesRemaining的值。变量的值不会持久存在。我不确定我做错了什么。 这是源代码:

public class MainActivity extends AppCompatActivity {

    private TextView swipes;
    private int swipesRemaining = 11;
    private static final String SWIPES = "swipes";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        swipes = (TextView) findViewById(R.id.textView);
        loadInt();

        if(savedInstanceState != null) {
            swipesRemaining = savedInstanceState.getInt(SWIPES);
        }

        updateText(swipesRemaining);
    }

    public void save(View view) {
        saveInt("key", swipesRemaining);
    }

    public void reset(View view) {
        swipesRemaining = 11;
        updateText(swipesRemaining);
    }

    public void swipe(View view) {
        if(swipesRemaining > 1) {
            swipesRemaining--;
            updateText(swipesRemaining);
        } else {
            Toast toast = Toast.makeText(this, "You ran out of swipes!...Resetting", Toast.LENGTH_SHORT);
            toast.show();
            reset(view);
        }
    }

    private void updateText(int swipesRemaining) {
        swipes.setText("Swipes: " + swipesRemaining);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putInt(SWIPES, swipesRemaining );
        super.onSaveInstanceState(savedInstanceState);
    }

    private void saveInt(String key, int value) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key, value);
        editor.commit();
    }

    private void loadInt() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        swipesRemaining = sharedPreferences.getInt("key", swipesRemaining);

        Toast toast = Toast.makeText(this, "Swipes left: " + swipesRemaining, Toast.LENGTH_SHORT);
        toast.show();
    }
}

0 个答案:

没有答案