共享首选项不会在重新打开活动时检索值

时间:2018-06-16 19:54:59

标签: java android performance sharedpreferences

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

例如:每次按钮点击硬币值增加到10点。现在,当我完全销毁应用程序并再次打开它时,点值应显示相同,而不是零。 我试图实现共享首选项以保存硬币但在退出应用程序后,当我重新打开它时,硬币像往常一样变为零。

这是我的代码

public class BooksActivity extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private TextView mText;
private int coinCount;
private CardView book;


public static final String PREFS_NAME = "MyPrefsFile";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_books);
    MobileAds.initialize(this, R.string.mypublisherid);

    SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME,0);
    coinCount = sharedPreferences.getInt("coins", coinCount);

    mText = (TextView) findViewById(R.id.mText);
    coinCount = 0;
    mText.setText(" " + coinCount);
    SharedPreferences sharedpreferences = getSharedPreferences(PREFS_NAME,0);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putInt("coins", coinCount);
    editor.commit();


    mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
    mRewardedVideoAd.setRewardedVideoAdListener(this);



    loadRewardedVideoAd();


    book = (CardView) findViewById(R.id.book_one);
    book.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (coinCount <= 29) {
                //if(coinCount <30) {
                new MaterialStyledDialog.Builder(BooksActivity.this)
                        .setTitle("Not Enough Coins")
                        .setDescription("Watch Ads To earn coins")
                        .setIcon(R.drawable.money)
                        .withIconAnimation(true)
                        .withDialogAnimation(true)
                        .setHeaderColor(R.color.colorPrimaryDark)
                        .setPositiveText("Of Course!")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                mRewardedVideoAd.show();
                            }
                        })
                        .setNegativeText("Not Now")
                        .onNeutral(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .show();

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

            }
        }
    });
}


private void loadRewardedVideoAd() {
    mRewardedVideoAd.loadAd(R.string.mypublisherid,
            new AdRequest.Builder().build());
}

@Override
public void onRewardedVideoAdLoaded() {

}

@Override
public void onRewardedVideoAdOpened() {

}

@Override
public void onRewardedVideoStarted() {

}

@Override
public void onRewardedVideoAdClosed() {
    loadRewardedVideoAd();

}

@Override
public void onRewarded(RewardItem rewardItem) {
    addCoins(rewardItem.getAmount());

}

private void addCoins(int amount) {
    coinCount += amount;
    mText.setText(" " + coinCount);

}

@Override
public void onRewardedVideoAdLeftApplication() {

}

@Override
public void onRewardedVideoAdFailedToLoad(int i) {

    Toast.makeText(BooksActivity.this, "Check your network connection", Toast.LENGTH_SHORT).show();

}
@Override
public void onResume() {
    mRewardedVideoAd.resume(this);
    super.onResume();
}

@Override
public void onPause() {
    mRewardedVideoAd.pause(this);
    super.onPause();
}

@Override
public void onDestroy() {
    mRewardedVideoAd.destroy(this);
    super.onDestroy();
}

public void startVideoAd(View view) {
    mRewardedVideoAd.show();
}

}

请在代码中告诉我做错了什么。

3 个答案:

答案 0 :(得分:2)

每次创建Activity时,都会将您的偏好值重新编写为0.因此,每次创建Activity时,根据SharedPreferences的计数为0。

在您的函数addCoins()中增加值,但永远不会更新SharedPreferences中的值。如果目标是在Activity启动的多个实例中保留您的值,则每次创建Activity时都需要停止将值重写为0。然后,如果您希望在SharedPreferences中更新增量值,则每次递增时都需要更新SharedPreferences中的值,或者Activity暂停OnPause()时更新值

答案 1 :(得分:1)

您只能在onCreate中使用SharedPreference编辑器保存coinCount,然后将其设置为0.它按预期工作。

尝试在coinCount实际更改后保存。

答案 2 :(得分:1)

步骤1,在onCreate

中使用之前初始化cointCount
private int cointCount = 0

第2步,请勿覆盖onCreate中的存储值,因此请从onCreate方法中删除这些行

coinCount = 0;
SharedPreferences sharedpreferences = getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("coins", coinCount);
editor.commit();

第3步,在addCoins中更新

private void addCoins(int amount) {
    coinCount += amount;
    mText.setText(" " + coinCount);

    SharedPreferences sharedpreferences = getSharedPreferences(PREFS_NAME,0);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putInt("coins", coinCount);
    editor.apply();
}

或者,将更新代码放在onPause中,这样就不会经常运行它。