I have an android application which runs a service at start. inside my MainActivity I write data into sharedPreferences:
String id="something";
SharedPreferences sp = this.getPreferences(this.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("opt", id);
editor.commit();
I want to read the data inside running service but the output is "empty":
String content="empty";
SharedPreferences settings = this.getApplication().getSharedPreferences("settings",Context.MODE_PRIVATE);
content =settings.getString("opt", "empty");
Log.i("opt:",opt); // Logs "empty"
Are SharedPreferences shared between service and application? or something else is wrong?
While adding, you are using default private shared preference but while getting value, you are calling special named shared preference ("settings"). This calls another file named "settings". This is why your value is empty. Default one and named("settings") shared preferences are different.