0

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?

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.