Ted pottel
Ted pottel

Reputation: 6983

Android set preferences not saving data

I'm writing a simple photo gallery app. I want people to scroll through the images and have the ability to add them to a 'favorites' list.

I have constructed a Favorite class that's global (put the class in a cGlobal class that defines it as static).

Now I have this working and I want to be able to save the state of the favorite -- the idea is as follows:

  1. When the app first starts up, it will load the favorites list from the preferences in the main activity.
  2. In the gallery activity it will save the favorite state in the preferences.

It seems like when I load the preferences form the main activity it comes up as null. But I can read what I write to it in the gallery activity. I have the following test code:

In main Activity, when the app starts:

//////////////////////////////////////////////////////////////////////////////////

public class MainActivity extends cBaseView  implements OnClickListener {
    /** Called when the activity is first created. */

    String tr;

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            // load in favrets from prefences
            SharedPreferences pre=getPreferences(MODE_PRIVATE);

// This does not work and tr is equal to no value.
            tr=pre.getString("label","no value");

            // add listeners

///////////////////////////////////////////////////////////////////////////////

Gallery Activity

public void onCreate(Bundle savedInstanceState) {      
    // test code
    SharedPreferences pre=getPreferences(MODE_PRIVATE);
    pre.edit().putString("label","ted").commit();

    // tr is set to ted, got the data
    tr=pre.getString("label","no value");
}

Upvotes: 0

Views: 145

Answers (1)

Snicolas
Snicolas

Reputation: 38168

When you use getPreferences, here is what you get, according to the javadoc of activity :

Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.

You should getSharedPreferences with the same name, to get preferences shared by different activities.

Upvotes: 2

Related Questions