简体   繁体   English

重新打开应用程序后,Android SharedPreferences无法保存

[英]Android SharedPreferences does not save after app reopening

I'm trying to use SharedPreferences with a very simple app it is just a TextView with number 0 and one button to increment this number, but after reopening the app and press the button it resets to 0 我正在尝试通过一个非常简单的应用程序使用SharedPreferences ,它只是一个数字为0的TextView和一个用于递增该数字的按钮,但是在重新打开该应用程序并按下按钮后,它将重置为0
Here is the code: 这是代码:

public class MainActivity extends AppCompatActivity {

public TextView t1;
public Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1=(Button)findViewById(R.id.button);
    t1=(TextView)findViewById(R.id.textView);

    SharedPreferences mypref=getSharedPreferences("file",MODE_PRIVATE);
    int n=mypref.getInt("n",0);
    String s=""+n;
    t1.setText(s);
    SharedPreferences.Editor editor=mypref.edit();
    editor.putInt("n",0);
    editor.apply();

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            add();
        }
    });
}

The add method: add方法:

private void add() {
    SharedPreferences mypref=getSharedPreferences("file",MODE_PRIVATE);
    SharedPreferences.Editor editor=mypref.edit();
    int n=mypref.getInt("n",0);
    n++;
    String s=""+n;
    t1.setText(s);
    editor.putInt("n",n);
    editor.apply();

}

You have this code every time your activity is created (same goes when you open the app): 每次创建活动时,您都有以下代码(打开应用程序时也是如此):

SharedPreferences mypref=getSharedPreferences("file",MODE_PRIVATE);
int n=mypref.getInt("n",0);
String s=""+n;
t1.setText(s);

// here  you reset the counter to 0
SharedPreferences.Editor editor=mypref.edit();
editor.putInt("n",0);
editor.apply();
// the problem ends here

So, to fix the problem simply remove the code between comments 因此,要解决此问题,只需删除注释之间的代码

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

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