簡體   English   中英

重新打開應用程序后,Android SharedPreferences無法保存

[英]Android SharedPreferences does not save after app reopening

我正在嘗試通過一個非常簡單的應用程序使用SharedPreferences ,它只是一個數字為0的TextView和一個用於遞增該數字的按鈕,但是在重新打開該應用程序並按下按鈕后,它將重置為0
這是代碼:

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

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

}

每次創建活動時,您都有以下代碼(打開應用程序時也是如此):

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

因此,要解決此問題,只需刪除注釋之間的代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM