glassraven glassraven - 6 days ago 8
Android Question

Android: issue with data storage (SharedPreferences)

I'm learning android and for this project I need to save user's data - color change of buttons, in this case -. During the program the change occurs (onClick), but when I restart the app, nothing happens - the change has not been saved (or read...) Can someone help me? Code:

final String paintKey = "paint";

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

buttonCreate();
preferences();
togglePlay();
}

public void preferences(){ //the issue in this method?

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
settings.getBoolean(paintKey,false);

String backGround = settings.getString("stage", "Indoors");

if (backGround.equals("Indoors")) {
Picasso.with(this).load(R.drawable.shocked_crowd).fit().centerCrop().into(stage);

}
if (backGround.equals("Street")) {
Picasso.with(this).load(R.drawable.coins).fit().centerCrop().into(stage);

}
}

public void changeColor(){
if(!paint) { //paint variable has global scope and it is set to false
c1.setBackgroundColor(Color.YELLOW);

paint = true;
}else{
c1.setBackgroundColor(Color.BLUE);

paint = false;
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("paint", paint);
editor.commit();
}


EDIT: the onClick method:

public void onClick(View v) {

if(v==color){

changeColor();
}


EDIT: this is how I have it now:

public void preferences(){

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
final String paintKey = "paint";
settings.getBoolean(paintKey,false);


Wrong? if I put editor instead of settings i get red underlined

Answer

In order to work with SharedPreferences you need a global key

final String paintKey = "paint"

To write boolean value info SharedPreferences use

SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(paintKey, paint).commit();

To read that data later

paint = settings.getBoolean(paintKey, false);
Comments