2016-07-14 55 views
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(); 

} 
+0

删除这些行'SharedPreferences.Editor编辑= mypref.edit()评论之间的代码; editor.putInt(“n”,0); editor.apply();' –

+0

谢谢@SagarJogadia – Goba

回答

0

你有这样的代码,您的每一次活动创建(也一样,当你打开应用程序):

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 

因此,要解决这个问题只需删除

+0

我的愚蠢错误....谢谢 – Goba