Search code examples
androidandroid-activitypreferencessharedlifecycle

Shared Preference not saving value


I am just learning to build some applications in Android. Out of curiosity, I have a small and weird problem using Shared Preferences. If someone can help me addressing this issue , I would be most thankful to them. Anyways,here goes the problem. I have 2 Activities. 1. Activity 1 : Consists of just one button that will get you to the next activity. 2. Activity 2 : Consists of a listview with checkbox (simple_list_item_checked or simple_list_multi_choice_item).

My question is: I open my application, hit the button on my first activity screen, this moves me to the second activity. I check an item in the listview. I hit the back button on my phone, go to the first activity, again press the button on my activity 1 screen, this takes me to the list again. Now I just leave my list item checked(I don't change anything that is already checked previously). Now again, I hit back button on my phone, get back to activity one. Now again when I press the button on my activity one screen. It takes me back to the listview but SURPRISINGLY nothing is checked. To note a point here, I had also set and retrieved my shared preference.

MY QUESTION IN A SINGLE LINE IS : If I don't change a value in the check list while I'm in that Activity and then go back to the Main Activity, and get back to the same check list activity, my shared preference does not load what has been saved earlier. Is this the normal behavior of Shared Preference or is it a problem in the coding.

I would just like to know how preference values are saved and retrieved and how long does a preference save a value ? I mean the lifecycle of the saved value in preference.

MY SECOND QUESTION : Also, I would like to know one more thing in activity life cycle. When I am in the second activity as explained in the above example. Now I press the home button , now I go to the background tasks and clear all the tasks(Apps) that are running . Now, my question is which state of activity life cycle is followed or what will be the final activity lifecycle before i clear all my apps from the background ? Please someone help me out on this. Thanks to all those creative developers out there in advance. Hope someone can solve my issue.

public class Secondact extends ListActivity {
    ListView list;
    SharedPreferences pref;
     int pos,itemposition,positionvalue;
     boolean boolval,checkvalue;
     SharedPreferences.Editor editor;
     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
          // setContentView(R.layout.secondact);
            Toast.makeText(getApplicationContext(), "ONCREATE", 50).show();

            list=getListView();

           String[] family_array=this.getResources().getStringArray(R.array.family);
           ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,family_array);
           list.setAdapter(adapter);
           list.setChoiceMode(1);
           pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         pos=pref.getInt("itempos", pos);
             boolval=pref.getBoolean("boolvalue", true);
            list.setItemChecked(pos, boolval);
            Toast.makeText(getApplicationContext(), "DATA LOADED ITEM NO:"+pos, 50).show();

           list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub


                pos=position;
                list.setItemChecked(pos, true);
                pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                editor=pref.edit();
                editor.putInt("itempos", pos);
                editor.putBoolean("boolvalue", list.isItemChecked(pos));
                editor.commit();
            }
        });

}

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
     editor=pref.edit();
        editor.putInt("itempos", pos);
        editor.putBoolean("boolvalue", list.isItemChecked(pos));
        editor.commit();
    //  Toast.makeText(getApplicationContext(), "PAUSE", 50).show();

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         pos=pref.getInt("itempos", pos);
         boolval=pref.getBoolean("boolvalue", true);
        list.setItemChecked(pos, boolval);
        //Toast.makeText(getApplicationContext(), "RESUME", 50).show();

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         editor=pref.edit();
        editor.putInt("itempos", pos);
        editor.putBoolean("boolvalue", list.isItemChecked(pos));
        editor.commit();
        Toast.makeText(getApplicationContext(), "DESTROY", 50).show();
        Toast.makeText(getApplicationContext(), "DATA SAVED ITEM NO:"+pos, 50).show();

    }

    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
     pos=pref.getInt("itempos", pos);
         boolval=pref.getBoolean("boolvalue", true);
        list.setItemChecked(pos, boolval);
        //Toast.makeText(getApplicationContext(), "RESTART", 50).show();

    }

    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        savedInstanceState.putInt("itempositionno", positionvalue);
        savedInstanceState.putBoolean("checkvalue", true);
        Toast.makeText(getApplicationContext(), "ONSAVEINSTANCE", 50).show();
        list.setItemChecked(pos, checkvalue);
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        pos=savedInstanceState.getInt("itempositionno", pos);
         checkvalue=savedInstanceState.getBoolean("checkvalue", true);
        list.setItemChecked(pos, checkvalue);
        Toast.makeText(getApplicationContext(), "ONRESTOREINSTANCE", 50).show();
        super.onRestoreInstanceState(savedInstanceState);
    }




}

Solution

  • I would just like to know how preference values are saved and retrieved and how long does a preference save a value ? I mean the lifecycle of the saved value in preference.

    A single line reply to your single line question -

    • It is saved throughout the life-cycle of the application unless you yourself clear it.

    To obtain shared preferences:

    SharedPreferences prefs = this.getSharedPreferences(
          "com.example.app", Context.MODE_PRIVATE);
    

    To read preferences:

    String dateTimeKey = "com.example.app.datetime";
    
    // use a default value using new Date()
    long l = prefs.getLong(dateTimeKey, new Date().getTime()); 
    

    To edit and save preferences

    In order to edit(clear) -

    SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.commit();
    

    In order to save -

    Date dt = getSomeDate();
    prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();
    

    Read - how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values.

    Which state of activity life cycle is followed or what will be the final activity life-cycle before I clear all my apps from the background ?

    Depends on your requirement. No need to follow final activity life-cycle to do this. For example - When the user logs out from the application, preferences related to the user are of no use and can be cleared independent of the life-cycle just after the log out button press.