-1

I am creating an app in which coins/points increases on watching reward video ads and those coins/points should be saved in the app

For example: every time on button click the coins value increases to 10 points. Now when I completely destroy the app and open it again, the points value should show the same, not zero

Here is my code

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

        }

    } 
});

My queston is how to Save The Coin value in Shared Preferences and retrieve it ?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Joy Dey
  • 563
  • 1
  • 5
  • 17
  • 5
    Possible duplicate of [How to use SharedPreferences in Android to store, fetch and edit values](https://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values) – achAmháin Jun 14 '18 at 14:59

1 Answers1

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

There's documentation here: https://developer.android.com/training/data-storage/shared-preferences

Neel Kamath
  • 1,188
  • 16
  • 34