Problems with Sharedpreferences

Asked

Viewed 90 times

1

I’m not able to save the value obtained rewardItem mine to be displayed in a Textview, every time I close the application and return to the same value and 0. Can someone help me with this mistake?

This is my main activity code, where I try to save. if it is possible correct him 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);
}

}

  • Are you loading the value in Textview as soon as your Activity opens? By your code it seems that you only increase the value once a reward is received.

1 answer

1


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

Try it this way:

@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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.