Q:

Android SharedPreferences does not save after app reopening

I'm trying to use SharedPreferences with a very simple app 
it is just a TextView with number 0 and one button to increment this number, but after reopening the app and press the button it resets to 0
Here is the code:
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();
        }
    });
}

The add method:
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();

}

A:

You have this code every time your activity is created (same goes when you open the app):
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

So, to fix the problem simply remove the code between comments

