如何使用共享首选项保存用户硬币

时间:2018-06-14 14:57:32

标签: java android performance sharedpreferences

我正在创建一个应用,其中观看奖励视频广告时硬币/点数会增加,并且应该在应用中保存这些硬币/点数

例如:每次按钮点击硬币值增加到10点。现在,当我完全销毁应用程序并再次打开它时,点值应显示相同,而不是零

这是我的代码

private TextView mText;
private int coinCount;
mText = (TextView) 
findViewById(R.id.money);
coinCount = 0;
mText.setText(" " + coinCount);


Button button = (Button) 
findViewById(R.id.buynow);
button.setOnClickListener(new.   
View.OnClickListener() {
@Override
public void onClick(View v) {
    if (coinCount <= 29) {
        //if(coinCount <30) {
        new MaterialStyledDialog.Builder(MainActivity.this)
                .setTitle("Not Enough Coins")
                .setDescription("Watch the Ad To Get 10 coins")
                .setIcon(R.drawable.ic_money)
                .withIconAnimation(true)
                .withDialogAnimation(true)
                .withDarkerOverlay(true)
                .setHeaderColor(R.color.color)
                .setPositiveText("Get some coins")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mRewardedVideoAd.show();
                    }
                })

                .show();

    } else {
            coinCount = coinCount - 30;
            mText.setText(String.valueOf(coinCount));

        }

    } 
});

我的问题是如何在共享首选项中保存硬币值并检索它?

1 个答案:

答案 0 :(得分:1)

SharedPreferences preferences = Context.getSharedPreferences("fileName", Context.MODE_PRIVATE);
preferences.edit().putString("coins", 10).apply();
preferences.getString("coins", "value if not yet set"); 

这里有文档:https://developer.android.com/training/data-storage/shared-preferences