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