Answer the question
In order to leave comments, you need to log in
Java SharedPreferences how to store multiple options?
How to store two values in SharedPreferences? Always outputs only SAVED_TEXT and SAVED_TEXT_TWO is not used.
Button btnLoad, btnSave;
EditText inputText, inputTextTwo;
SharedPreferences sPref;
final String SAVED_TEXT = "saved_text";
final String SAVED_TEXT_TWO = "saved_text_two";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputText = (EditText) findViewById(R.id.inputText);
inputTextTwo = (EditText) findViewById(R.id.inputTextTwo);
btnLoad = (Button) findViewById(R.id.btnLoad);
btnLoad.setOnClickListener(this);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
loadText();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case (R.id.btnLoad):
loadText();
break;
case (R.id.btnSave):
saveText();
break;
}
}
void saveText() {
sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TEXT, inputText.getText().toString());
ed.putString(SAVED_TEXT_TWO, inputTextTwo.getText().toString());
ed.commit();
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(SAVED_TEXT, "");
String savedTextTwo = sPref.getString(SAVED_TEXT_TWO, "");
inputText.setText(savedText);
inputTextTwo.setText(savedTextTwo);
Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question