androidsharedpreferencessavestate

Shared Prefs with a Boolean


i´d like to save a simple setting or more boolean with sharedPrefs. If the user clicks on the "button", button2 is supposed to change its alpha. However, if i close the app, the alpha value of 0.25f is gone and button2 has the same alpha value like before. I´m sure that there is something wrong with my sharedPrefs but i dont know what.

I´m kind of new in java. So i hope u could help me solve this problem :).

Thanks fot any help!

public class MainActivity extends AppCompatActivity {

Button button, button2;
Boolean click;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    button2 = (Button) findViewById(R.id.button2);

    click = false;

    final SharedPreferences sharedPreferences = getSharedPreferences("sharedPrefName", Context.MODE_PRIVATE);
    click= sharedPreferences.getBoolean("lockedState", true);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            click = true;
            SharedPreferences.Editor editor= sharedPreferences.edit();
            editor.putBoolean("lockedState", click);
            editor.apply();

            button2.setAlpha(0.25f);

        }
    });


}

}


Solution

  • in onCreate under this click= sharedPreferences.getBoolean("lockedState", false);

    add these lines:

    if(click)
       button2.setAlpha(0.25f);
    else
       button2.setAlpha(1f);