2016-07-14 28 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

相關問題