Shared Preferences Between Activities – How to Retrieve Values

September 25, 2012 Zaidi Android Development Tutorials

It can be tricky or frustrating when your application needs to share data between two or more activities in a very simple way. I am saying this from my own experince especially when I started developing Android apps. Soon you will realize how simple it is to store strings or numbers and retrieve between activities.

By creating SharedPreferences object, you can accomplish just that and your data will be persistance. Depending on what kind of application you are doing, the data can be anything from log in information, todo list or anything that can be stored in the key/value form.

To illustrate this, look at the two activities below. The first activity creates a shared file that will be accessed with two or more activities. I do assume that you can create a new project since I will not cover that part.

Create your first activity and give it any name. My activity keeps track of team’s score. Layout file is not shown in the example but I will reference each view that is in the layout.


Now lets access scores stored in SharedPreferences object. Again, layout file is not included below but I am going to initiate and reference all the views from it. Pay attention on how I access the SharedPreferences file.


To show a score for a specific team, a user will type in team’s name and press the “Show Score” button. If a user misspelled team’s name or one that’s not stored, the “Team not found” message will be displayed.

As you can see, shared preferences between activity above has been accomplished by accessing the file name that is declared as constant in TeamScore activity. All data stored in the file can be accessed by creating SharedPreferences the same way. This will not work for Shared Preferences between applications.

retrieve sharedpreferences valuessharedpreferencessharedpreferences between activities

One Response to “Shared Preferences Between Activities – How to Retrieve Values”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Powered by WordPress and HQ Premium Themes.