Broak
Broak

Reputation: 4187

Shared Preferences not being saved (ever) in fragment?

appPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

Also tried by creating a new prefs file by name, on both the activity and fragment, still nothing.

        boolean firstRun = appPrefs.getBoolean("firstrun", true);
        if (firstRun) {
            rotate_hint.setVisibility(View.VISIBLE);
        } else {
            rotate_hint.setVisibility(View.GONE);
        }

always, always, returns true.

public void hide_list_hint() {
    if (rotate_hint.getVisibility() == View.VISIBLE) {
        rotate_hint.setVisibility(View.GONE);
        Editor prefsEditor;
        prefsEditor = appPrefs.edit();
        prefsEditor.putBoolean("firstrun", true); <- facepalm
        prefsEditor.commit();
    }
}

I dont know of a way to perhaps try this in the fragments onCreate or onActivityCreated because i need access to the 'rotate_hint' view, which comes from the inflated view in the onCreateView.

Upvotes: 0

Views: 442

Answers (2)

FxRi4
FxRi4

Reputation: 1248

i should note to your code where :
1-

appPrefs.getBoolean("firstrun", true);

if you not save "fristrun" key the defult value will be true i Guess it should be false
2-

if (rotate_hint.getVisibility() == View.VISIBLE) {}

you should save your state of Visibility true in this if and on else save false for this state (for better Readability)

i use this saving and restoring method on my fragment as :
for restoring One CheckBox :

public void onViewCreated(View view, Bundle savedInstanceState) {
    SharedPreferences Setting = getSherlockActivity()
            .getSharedPreferences(PREFERENCENAME, 0);
    boolean Check=Setting.getBoolean(
            "NotifyChange", false);
    CheckBox Changebox = (CheckBox) view.findViewById(
            R.id.checkbox);
    Changebox.setChecked(Check);
}

and for saving state of CheckBox :

public void onDestroyView() {
    // TODO Auto-generated method stub
    super.onDestroyView();
    CheckBox Changebox = (CheckBox) getView().findViewById(
            R.id.checkbox);
    SharedPreferences Setting = getSherlockActivity()
            .getSharedPreferences(PREFERENCENAME, 0);
    Editor editor = Setting.edit();
    editor.putBoolean("NotifyChange",Changebox.isChecked);
    editor.commit();

hope to be useful :)

Upvotes: 1

slhddn
slhddn

Reputation: 1997

You put true, if null you get true. Of course it will return true. Change this line;

prefsEditor.putBoolean("firstrun", false);

Upvotes: 2

Related Questions