Search code examples
androidpreferences

Android Preference old and new value compare


I have got NewValue from activity1 and store on preference and compare with OldValue from activity2: my problem it dose not store oldValue..

on activity 1:

  int i = 5;      

  SharedPreferences prefs1 = getPreferences(0);
  SharedPreferences.Editor editor = getPreferences(0).edit();
  editor.putInt("new", i);
  editor.commit();

on activity 2:

    SharedPreferences prefs1 = getPreferences(0);
    int oldValue = prefs1.getInt("old", 0);
    int newValue = prefs1.getInt("new", 0);

    /* Should Activity Check for Updates Now? */
    if (oldValue < newValue) {

        /* Save current newValue for next Check */
        SharedPreferences.Editor editor = getPreferences(0).edit();
        editor.putInt("old", newValue);
        editor.commit();

        do something....

    }

Solution

  • Well, if you want share preferences with activities then you need to use getSharedPreferences(String, int) but you are using getSharedPreferences(int)

    getSharedPreferences(int)

    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.

    get SharedPreference object like this

    SharedPreferences prefs1 =getSharedPreferences ("app_prefs", Context.MODE_PRIVATE);