SharedPreference
is just a file you can save and retrieve values from. Here are the simplest steps to use a SharedPreference
in your activity:
You need to make a variable sP
which will point at the SharedPreferences
file you will use:
SharedPreferences sP = getSharedPreferences("MyPrefs", MODE_PRIVATE);
You need to make a variable sPeD
which will point at the "editor" for that file which will let you put values in to that file:
SharedPreferences.Editor sPeD = sP.edit();
You can then extract stored values from that file. The values are indexed by a "key" which is just a String
that you define:
String myString = sP.getString("keyTextYouDefine", "Oops!");
If there is no value stored at key "keyTextYouDefine"
then getString()
will make myString
equal to "Oops!"
.
In order to store a value at for that key, use this:
sPeD.putString("keyYouDefine","The string I want to save.");
sPeD.commit();
If you forget to do commit()
after you put things in the file, then they are not actually put there.
This should get you well on your way.
ADDED LATER:
You can then use this to determine which image is on the button.
Assuming you have propertly defined your button
Button button = findViewById(R.id.myButton) // or whatever you are actually using
then set image from whatever, if anything was stored in ShardPreference
int which = sP.getInt("WhichImage", 1); // assuming image1 is the "default"
switch (which) {
case 1:
button.setCompoundDrawables(null, @drawable/image1, null, null);
break;
case 2:
button.setCompoundDrawables(null, @drawable/image2, null, null);
break;
default: // no image
}
Elsewhere in your activity, when you have decided to switch button image to image2:
if (whatever) { // condition for changing to image 2
button.setCompoundDrawables(null, @drawable/image2, null, null);
sP.edit().putInt("WhichImage", 2).commit();
}
I have never used setCompoundDrawables()
myself, so your mileage may vary.