0
我試圖使用SharedPreferences
一個非常簡單的應用程序 它只是用數字0和一個按鈕TextView
來增加這個數字,但之後重新打開應用程序後不保存,並按下按鈕,重置爲0
下面是代碼:Android的SharedPreferences應用重啓
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.Editor編輯= mypref.edit()評論之間的代碼; editor.putInt(「n」,0); editor.apply();' –
謝謝@SagarJogadia – Goba