Samo Poláček Samo Poláček - 1 year ago 96
Android Question

Android SharedPreferences successfully not working

I'm newbie into android and today I wanted to implement some SharedPreferences.

Here's my code: (or Image if ou like it more)

public void onCreate(Bundle savedInstanceState) {

// Initialize Shared Preferences
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyData", Context.MODE_PRIVATE);

sharedPreferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
logMsg(sharedPreferences.toString() + "=>" + s + "=>" + sharedPreferences.getString(s, ""));

final EditText etId = (EditText) findViewById(;
final EditText etValue = (EditText) findViewById(;

Button btnSave = (Button) findViewById(;
btnSave.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// set Data
logMsg("Id= " + etId.getText().toString() + " Value= " + etValue.getText().toString());
sharedPreferences.edit().putString(etId.getText().toString(), etValue.getText().toString());
if (sharedPreferences.edit().commit()){
}else {

// get Data
logMsg("Id= '" + etId.getText().toString() + "' Value= " + sharedPreferences.getString(etId.getText().toString(), "No Value"));


The problem is that after pressing btn_save log says Success on
but after that I don't retrieve any data with
(respectively I retrieve dafault value that is in my case "No Value").

Do you have any idea what's wrong?
Is it necessary to unregister SharedPreferences.OnSharedPreferenceChangeListener?


Answer Source

Each time you call edit(), you get a new instance of SharedPreferences.Editor. You need to do your modifications and commit() (or apply()) on the same editor instance.

Therefore, save the return value of edit() to a variable, and call putString() and commit() on that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download