Shared Preferences Between Activities – How to Retrieve Values

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.

This entry was posted in Android Development Tutorials and tagged , , . Bookmark the permalink.

2 Responses to Shared Preferences Between Activities – How to Retrieve Values

  1. Sergey says:

    Hello,
    I find your code very useful BUT in second code in line 37 “getInt” is red. It says “Cannot resolve metod”. I will be very happy if you could help me.
    Thanks in advance,
    Sergey

  2. Pingback: SharedPreferences Across Applications | ZaidiSoft

Comments are closed.