I’m new to Android and I don’t know how to retrive the values stored using sharedpreferences, I couldn’t find any example of what I have to write on the other activity to use these values. If someone can help me I would really appreciate it
This is how I am storing the data:
protected void onResume() {
super.onResume();
SharedPreferences prefs = getPreferences(0);
String restoredText1 = prefs.getString("cpw", "30");
if (restoredText1 != null) {
savedcostperworker.setText(restoredText1, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
if (selectionStart != -1 && selectionEnd != -1) {
savedcostperworker.setSelection(selectionStart, selectionEnd);
}
}
}
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putString("cpw", savedcostperworker.getText().toString());
editor.putInt("selection-start", savedcostperworker.getSelectionStart());
editor.putInt("selection-end", savedcostperworker.getSelectionEnd());
}
private EditText savedcostperworker;
Now I want to show the value “cpw” in a TextView in another activity, but I don’t know how
You forgot to call
commit()to save your Editor changes:Simply call
getSharedPreferences()with the first Activity’s name and use it like before:You cannot use
getPreferences()in the second Activity because it will callgetSharedPreferences()with the wrong file name. SeegetPreferences()documentation for more information.