How to properly save values in Android memory
Shared Preferences is a way to permanently save values that you may need every time the user opens your app. Such values are not only the settings, but also you may need to save some other values such as a username or email (if your app needs login).
An easy way to properly use this feature is shown below.
1. First get an instance of SharedPreferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
2. If you want to write a value to the memory, you first need to get an instance of Editor:
SharedPreferences.Editor editor = preferences.edit();
3. Then, you can write values in memory, which are uniquely defined by a name:
editor.putBoolean("name_of_value_1", true);
editor.putString("name_of_value_2", "hello world");
editor.commit();
4. While reading a saved value, you must also define the default value, which is used when the
required variable hasn't been saved yet. To read a value, you don't need the editor!
value_1 = sp.getBoolean("name_of_value_1", false);
value_2 = sp.getString("name_of_value_2", "default");
Here, the dafault values are false for the first one, and default for the second one.
How to properly save values in Android memory
Reviewed by Michail Theofilatos
on
21:36
Rating:
Reviewed by Michail Theofilatos
on
21:36
Rating:

No comments: