Reputation: 191
I am trying to retrieve boolean from SharedPreferences
but boolean is always on false.
The code:
SharedPreferences prefs;
boolean crosshairIsShown;
...
prefs = getSharedPreferences("Weapon1", MODE_PRIVATE);
crosshairIsShown = prefs.getBoolean("crosshairIsShown", false);
crosshair();
..
crosshair.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (crosshairIsShown == false) {
crosshairIsShown = true;
crosshair1.setVisibility(View.VISIBLE);
crosshair2.setVisibility(View.VISIBLE);
crosshair.setImageResource(R.drawable.crosshair_enabled);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("crosshairIsShown", true);
editor.commit();
} else {
crosshairIsShown = false;
crosshair1.setVisibility(View.INVISIBLE);
crosshair2.setVisibility(View.INVISIBLE);
crosshair.setImageResource(R.drawable.crosshair_disabled);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("crosshairIsShown", false);
editor.commit();
}
}
});
...
private void crosshair() {
if (crosshairIsShown == false) {
crosshair1.setVisibility(View.VISIBLE);
crosshair2.setVisibility(View.VISIBLE);
crosshair.setImageResource(R.drawable.crosshair_enabled);
} else {
crosshair1.setVisibility(View.INVISIBLE);
crosshair2.setVisibility(View.INVISIBLE);
crosshair.setImageResource(R.drawable.crosshair_disabled);
}
}
Why is this happening? What did I do wrong?
Upvotes: 2
Views: 193
Reputation: 191
Use getBoolean for this pas "key" and "false"
boolean flag = getPreferences().getBoolean(key, false);
Upvotes: 0
Reputation: 11255
Use Below Method:
@Override
public boolean getBooleanValuesFromPreferences(String key) {
boolean data = getPreferences().getBoolean(key, false);
return data;
}
Upvotes: 1