【问题标题】:How to save and update points in a share preferences如何在共享首选项中保存和更新点
【发布时间】:2018-03-18 08:33:09
【问题描述】:

我有我的 BoostPoints 活动,供用户通过观看奖励视频广告来增加积分,是的,当用户观看广告时,积分会加起来,现在的问题是,当我关闭活动或应用程序时并重新打开它,积分回到零。例如,用户观看了广告并获得了 100 分,当用户关闭活动或应用程序而不使用这些积分并稍后再次打开时,积分消失并归零。我希望即使用户关闭应用并稍后打开应用,积分仍然可用,他们应该会在离开的地方看到积分。

我在onCreate(); 中尝试过这段代码

//Save Coins
    SharedPreferences saveCoins = this.getSharedPreferences("mySaverCoins", Context.MODE_PRIVATE);
    pointsAmount = saveCoins.getInt("C",0);

当我使用此代码运行我的应用程序时,它不会保存我的硬币,每次我启动它时它都会归零。

我也尝试在 `onCreate(); 中添加这一行

pointsAvailable.setText("C"+pointsAmount);

但是我的活动因为这条线而崩溃

我的完整 java.class 看起来像这样

public class BoostPoints extends AppCompatActivity  implements RewardedVideoAdListener {

public int pointsAmount = 0;

private RewardedVideoAd mAd;
Button freePoints;
TextView pointsAvailable;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_boost_points);

    getSupportActionBar().hide();


    MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544~3347511713");

    mAd = MobileAds.getRewardedVideoAdInstance(this);
    LoadRewardedVideoAd();
    mAd.setRewardedVideoAdListener(this);

    freePoints=(Button) findViewById(R.id.btnFreePoints);


    //Save Coins
    SharedPreferences saveCoins = this.getSharedPreferences("mySaverCoins", Context.MODE_PRIVATE);
    pointsAmount = saveCoins.getInt("C",0);


    //Update Coins
    pointsAvailable.setText("C"+pointsAmount); //This line crashes my activity

    //Show points available
    pointsAvailable = (TextView) findViewById(R.id.pointsAvailable);

}


public void FreePoints(View view) {
    if (mAd.isLoaded()){
        mAd.show();

    }
}

private void LoadRewardedVideoAd()
{
    if (!mAd.isLoaded()){
        mAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());

    }
}

@Override
public void onRewarded(RewardItem rewardItem) {
    pointsAmount = pointsAmount +10;
    pointsAvailable.setText("C"+pointsAmount);
}

}

我的代码可能有什么问题

【问题讨论】:

  • 将积分保存到首选项的代码?
  • 是的先生,这就是我想要的
  • 在下面查看我的答案

标签: java android


【解决方案1】:

您需要使用

int 转换为 String
pointsAvailable.setText("C"+String.valueOf(pointsAmount));

并且要保存积分,您需要将它们存储在SharedPreferences中的onRewarded中:

saveCoins.edit().putInt("C",pointsAmount).commit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-03
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多