Problems with Sharedpreferences

1

I am not able to save the rewardItem value obtained from my to be displayed in a TextView, every time I close the application and return the same value and 0. Can anyone help me with this error?

This is my main activity code, where I try to save. if it is possible, correct it for me ...

@Override
public void onRewarded(RewardItem rewardItem)
{
    addCoins(rewardItem.getAmount());
    SharedPreferences sps = getSharedPreferences("save_coins", AppCompatActivity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sps.edit();
    editor.putInt("my_coins", mCoinCount);
    editor.commit();
}

@Override
public void onRewardedVideoAdLeftApplication()
{

}

@Override
public void onRewardedVideoAdFailedToLoad(int i)
{

}
private void addCoins(int coins) {
    mCoinCount = mCoinCount + coins;

    SharedPreferences spg = getSharedPreferences("save_coins", AppCompatActivity.MODE_PRIVATE);
    int mCoinCount = spg.getInt("my_coins", 0);
    mCoinCountText.setText("Coins: " + mCoinCount);
}

}

    
asked by anonymous 13.09.2018 / 07:26

1 answer

0

I believe the value of mCoinCount is not updated when I start the App.

Try this:

@Override
protected void onResume() {
    super.onResume();
    loadAmount();
}

/**
 * Método responsável por carregar o valor do SharedPreferences,
 * e atuaizar a variavel mCoinCount
 */
private void loadAmount(){
    SharedPreferences sps = getSharedPreferences("save_coins", AppCompatActivity.MODE_PRIVATE);
    mCoinCount = sps.getInt("my_coins", 0);
    updateView();
}
public void onRewarded(RewardItem rewardItem)
{
    addCoins(rewardItem.getAmount());
    updateView();
}
/**
 * Soma o valor informado como parametro ao mCoinCount
 * e salva este valor no SharedPreferences
 * @param coins
 */
private void addCoins(int coins) {
    mCoinCount += coins;
    final SharedPreferences spg = getSharedPreferences("save_coins", AppCompatActivity.MODE_PRIVATE);
    SharedPreferences.Editor editor = spg.edit();
    editor.putInt("my_coins", mCoinCount);
    editor.commit();
}
/**
 * Atualiza o valor da tela
 */
private void updateView(){
    mCoinCountText.setText("Coins: " + mCoinCount);
}
    
14.09.2018 / 16:27