I am not sure why my code isn’t working, following the android developer guide this should work. I assume that it is because I don’t have a preferences file created, I am not sure how to go about that. Could someone take a look and see if I have written everything correctly?
public static final String PREFS_NAME = "TestPrefs";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Save(View v){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
final EditText s = (EditText) findViewById(R.id.editText1);
settings.edit().putString("TBox1", s.getText().toString());
settings.edit().commit();
}
public void Open(View v){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
final EditText s = (EditText) findViewById(R.id.editText1);
String newS = settings.getString("TBox1", "");
s.setText(newS);
}
You have to
commit()on the same Editor. Commiting on another object as you have done means that the previousputString()gets lost. This means changeto
Of course, if you have more than one thing to edit, you can keep a reference to your editor:
Eg: