简体   繁体   English

在更改SharedPreferences值时遇到问题

[英]Having problems with changing SharedPreferences value

I want to save a value ("Coins"), and I'm using the SharedPreferences option (I want that the number of coins will be saved even after closing the app). 我想保存一个值(“硬币”),我正在使用SharedPreferences选项(我希望即使关闭应用程序后也会保存硬币数量)。 I used 2 functions, one to insert (/change) the coins number, and another one to get it. 我使用了2个函数,一个用于插入(/更改)硬币编号,另一个用于获取硬币编号。 In addition, I made a button which after clicking on it, it changes the number of the coins. 另外,我做了一个按钮,点击它后,它改变了硬币的数量。 The problem is, that the button doesn't change it. 问题是,按钮不会改变它。 Any help? 有帮助吗? Thanks in advance. 提前致谢。

package com.myfirstapplication.owner.appversion1;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button btnPlay;

public void changeCoinsNumber(String key, int value) {
    SharedPreferences sharedPreferences = getSharedPreferences("PlayerInfo", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(key, value);
    editor.commit();
}

public int loadCoinsNumber(String key) {
    SharedPreferences sharedPreferences = getSharedPreferences("PlayerInfo", Activity.MODE_PRIVATE);
    int savedValue = sharedPreferences.getInt(key, 0);
    return savedValue;
}

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

    changeCoinsNumber("CoinsNumber", 5);

    TextView txt = (TextView) findViewById(R.id.spText);
    txt.setText(""+loadCoinsNumber("CoinsNumber")); // displaying the number of coins

    btnPlay = (Button) findViewById(R.id.btnPlay);
    btnPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            changeCoinsNumber("CoinsNumber", 111);
        }
    });
}

} }

You need to display it again if you change the coins value as per you code. 如果您根据代码更改硬币值,则需要再次显示它。 I am updating a small portion of your code. 我正在更新你的一小部分代码。

    final TextView txt = (TextView) findViewById(R.id.spText);//Make txt final
    txt.setText(""+loadCoinsNumber("CoinsNumber")); // displaying the number of coins

    btnPlay = (Button) findViewById(R.id.btnPlay);
    btnPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            changeCoinsNumber("CoinsNumber", 111);
            txt.setText(""+loadCoinsNumber("CoinsNumber"));//Adding this line to update
        }
    });

Hope it will help you :) 希望它能帮到你:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM