Ali Sheikhpour Ali Sheikhpour - 5 months ago 46
Android Question

Android sharedPreferences inside service is empty

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);

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?

Answer Source

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.

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