Samo Poláček Samo Poláček - 3 months ago 23
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)

@Override
public void onCreate(Bundle savedInstanceState) {
// SOME CODE HERE


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

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

final EditText etId = (EditText) findViewById(R.id.etId);
final EditText etValue = (EditText) findViewById(R.id.etValue);

Button btnSave = (Button) findViewById(R.id.btn_save);
btnSave.setOnClickListener(new OnClickListener() {
@Override
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()){
logMsg("Success");
}else {
logMsg("Fail");
}

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


//SOME CODE HERE
}


The problem is that after pressing btn_save log says Success on
sharedPreferences.edit().commit()
but after that I don't retrieve any data with
getString()
(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?

Thanks.

Answer

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.

Comments