Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

How to Preserve Program State Between Views

Here's the scenario:

  1. I have MainActivity.XML and one other view, let's call it SomeView.XML.
  2. I have an int someInt set = 0 in MainActivity.Java.
  3. Later in SomeView.Java is make a change so that this int someInt = 1

It seems, however, when I change between views, the state is not retained. In other words int someInt is once again = 0.

2 Answers

SharedPreferences worked for me here, and even saves the integer for subsequent launches of the app.

This line obtains shared preferences, which contain the rank of the user:

         rank = getPreferences(MODE_PRIVATE).getInt("UserRank", rank);

This line saves user's rank to shared preferences:

        getPreferences(MODE_PRIVATE).edit().putInt("UserRank", rank).commit();

I just got the latest edition of Android App Development for Dummies, which has a whole chapter on Shared Preferences. So hopefully that will help me better understand this topic.

Even if you use the same variable names between activities, they will represent different "boxes" in memory. One will not affect the other.

If you want to pass an integer from one activity to another (from your SomeView activity to your MainActivity) then you can do so by using the putExtra method on the intent that you create to go from one activity to another.

That sounds like a good idea... I've been reading about other options as well. I might try to use SharedPreferences to store the integer. Perhaps with Shared Preferences the int will even be retained if the Android device is powered off.