As far as I know, SharedPreferences allow us to store some simple data in a
named area in our phone. Introduction to the uses of SharedPreferences is very
clear at Android SDK website. I just copied here(I divided the contents into
four parts):
Introduction
The SharedPreferences
class
provides a general framework that allows you to save and retrieve persistent
key-value pairs of primitive data types. You can use SharedPreferences
to
save any primitive data: booleans, floats, ints, longs, and strings. This data
will persist across user sessions (even if your application is
killed).
Get SharedPreferences
object
To get a SharedPreferences
object
for your application, use one of two methods:
getSharedPreferences()
-
Use this if you need multiple preferences files identified by
name, which you specify with the first parameter.getPreferences()
-
Use this if you need only one preferences file for your
Activity. Because this will be the only preferences file for your Activity,
you don‘t supply a name.
Write the
values
To write values:
- Call
edit()
to
get aSharedPreferences.Editor
. - Add values with methods such as
putBoolean()
andputString()
. - Commit the new values with
commit()
Read the
values
To read values, use SharedPreferences
methods
such as getBoolean()
and getString()
.
_______________________________________________________________________________________________________________________
Now let‘s get into example time:
First, take a look at AndroidManifest.xml file to get to know it.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Two Activities exist in this example,
MainActivity.java which uses activity_main.xml as the content view;
Display.java which uses main.xml as the content view:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
We set up two values and store them in SharedPreferences object. These two
values can be changed in MainActivity.java, and would be displayed in
main.java.
SharedPreferences in Android,布布扣,bubuko.com