As you mentioned, for relatively small collection of key-values to save, use the SharedPreferences . A SharedPreferences
object indicates a file that contains key-value pairs and provides simple methods for reading and writing.
Each SharedPreferences file is managed by the framework
and can be private or shared.
You can first define a static string to give the name of your configuration and declare the image that will appear with the click of the button:
public static final String PREFS_NAME = "Preferences";
private ImageView img;
Then we create a method to be added to the image when the button is clicked and a preference is saved, like this:
private void onOff() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
settings.edit().putBoolean("online", true).apply();
boolean online = settings.getBoolean("online", false);
if (online) {
img.setImageResource(R.drawable.confirmacao);
} else {
img.setImageResource(R.drawable.fundo);
}
}
In order to redeem the recorded value, you can simply check the screen where the image is located:
img = (ImageView) findViewById(R.id.img);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Boolean online = settings.getBoolean("online", false);
if (online)
img.setImageResource(R.drawable.confirmacao);
else
img.setImageResource(R.drawable.fundo);
To end, you should put this onOff();
method on the button you want.
So, you'll do this checkup every time you log in to your app. Remember that it is a quick way to do and can be optimized. This is just a basic example so that you have more notion.
Comments:
1 - "img" is the id of the image that has no background defined in the layout and is where the confirmation image is inserted.
2 - "confrimation" is the name of the image file that represents the view notification.
3 - "background" is the name of a file of an image with nothing (transparent) saved in .png
4 - Perhaps the onOff();
method can be triggered on any button in my app because I use only one Activity in the whole app.
5 - There is a video on the article page "Beyond SQLite" (proposed below) that can help a lot.
There are other persistent, simple and agile alternative techniques that allow the persistence of small amounts of data. These are:
• PreferenceActivity
;
• Internal Storage
;
• Armazenamento em Cache
;
• External Storage
.
See some articles: