pantera
pantera

Reputation: 159

SharedPreferences clarification

I have 2 activities , In 2nd activity i put strings in to the Shared Preferences using editor and commit it.

when i return from 2nd activity to 1st activity to see the strings are not displayed displayed.

But when i kill the app/exit from it and Run the app again i am able to see the strings in the 1st Activity.

My Question: is SharedPreferences work this way?

Because the previous values are returned ,even after updating it to new values in 2nd activity.

1st activity has 2 textview only for displaying Strings.

2nd Activity to enter the 2 strings save and finish();return to 1st activity

1st activity in Oncreate method i fetch the shared pref and display

when moving to 2nd activity from 1st to 2nd i finish(); 1st activity;

Still new values are not Showing-up but only after reopening the app.

Upvotes: 0

Views: 71

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006604

so there is no need close the app to see the updated values?

No. However:

  • You must make sure that you actually reload your UI from the SharedPreferences in the first activity, either by using a lifecycle method that you are sure will be invoked (e.g., onResume()) or by using an OnSharedPreferenceChangeListener

  • You must have both activities in the same process (i.e., remove any android:process attributes from your manifest)

This sample project demonstrates editing preferences in one activity and displaying them in another activity.

Upvotes: 2

Steve Benett
Steve Benett

Reputation: 12933

I assume that your code about the SharedPreferences works because otherwise you will not see the same Strings again after you killed the App.

It's all about the moment to read and write the data into the preferences. If you leave an Activity onPause is the callback where to write your data to the preferences. Because it's the last callback you can count on to be fired in the lifecycle. Because you have to consider that the system can kill your Activity as well and onDestroy may not be invoked.

To read from the Preferences you should use onResume as the default option. In your case I think onStart works too. But overall onResume is the way to go.

This way you always write / read properly and your Activitys always shows the up to date data.

Upvotes: 2

Related Questions