In addition to SQLite databases, SharedPreferences is also a lightweight data storage method. Unlike file storage methods, SharedPreferences uses key-value data to store data. Moreover, SharedPreferences also supports a variety of different data types. Therefore, using SharedPreferences to persist data is much more convenient than using files. Let’s take a look at its specific usage.
How to store data into SharedPreferences
To use SharedPreferences to store data, you first need to obtain the SharedPreferences object. There are three main methods for obtaining SharedPreferences objects in Android.
In the classgetSharedPreferences()method
This method receives two parameters. The first parameter is used to specify the name of the SharedPreferences file. If the specified file does not exist, one will be created. The SharedPreferences files are stored in the /data/data//shared_prefs/ directory.
The second parameter is used to specify the operating mode. There are mainly two modes to choose from, MODE_PRIVATE and MODE_MULTI_PROCESS. MODE_PRIVATE is still the default operation mode, and the effect is the same as passing 0 directly, indicating that only the current application can read and write the SharedPreferences file. MODE_MULTI_PROCESS is generally used to read and write the same SharedPreferences file in multiple processes. Similarly, the two modes of MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE have been deprecated in Android 4.2 version.
In the classgetPreferences()method
This method and the getSharedPreferences() method in ContextVery similar, but it only receives one operation mode parameter, because when using this method, the currently active class name will be automatically used as the file name of SharedPreferences.
In the classgetDefaultSharedPreferences()method
This is a static method that takes a Context parameter and automatically names the SharedPreferences file using the current application's package name as a prefix.
After obtaining the SharedPreferences object, you can start storing data into the SharedPreferences file, which can be mainly divided into three steps.
1. Calling the SharedPreferences objectedit()Method to get an object.
2. Add data to the object, for example, if you add a boolean data, use the putBoolean method, and add a string, use the putString() method, and so on.
3. Callcommit()The method submits the added data to complete the data storage operation.
Before we knew it, we have introduced a lot of theoretical knowledge, so let’s quickly experience the usage of SharedPreferences storage through an example.
Create a new SharedPreferencesTest project, and then modify the code in activity_main.xml as follows:
<LinearLayout xmlns:andro android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android: android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save data" /> </LinearLayout>
Here we simply place a button to store some data into the SharedPreferences file.
Then modify the code in MainActivity as follows:
public class MainActivity extends Activity { private Button saveData; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); saveData = (Button) findViewById(.save_data); (new OnClickListener() { @Override public void onClick(View v) { editor = getSharedPreferences("data", MODE_PRIVATE).edit(); ("name", "Lily"); ("age", 26); ("married", false); (); } }); } }
You can see that here first registers a click event for the button, and then in the click event, the file name of SharedPreferences is specified as data through the getSharedPreferences() method, and the object is obtained. Then three pieces of data of different types are added to this object, and finally the commit() method is called to submit, thus completing the data storage operation.
Then we will naturally have to take a look at how to read these data from the SharedPreferences file.
Read data from SharedPreferences
A series of get methods are provided in the SharedPreferences object for reading stored data. Each get method corresponds to a put method in SharedPreferences. For example, when reading a Boolean data, use the getBoolean() method, and when reading a string, use the getString() method. These get methods all receive two parameters. The first parameter is the key. The key used when passing in to store data can get the corresponding value. The second parameter is the default value, which means what default value will be used to return when the passed key cannot find the corresponding value.
Let’s try it out through examples, and continue to develop based on the SharedPreferencesTest project and modify the code in activity_main.xml, as shown below:
<LinearLayout xmlns:andro android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android: android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save data" /> <Button android: android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Restore data" /> </LinearLayout>
A button to restore data is added here. We hope to read data from the SharedPreferences file by clicking this button.
Modify the code in MainActivity as follows:
public class MainActivity extends Activity { private Button saveData; private Button restoreData; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); saveData = (Button) findViewById(.save_data); restoreData = (Button) findViewById(.restore_data); …… (new OnClickListener() { @Override public void onClick(View v) { SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE); String name = ("name", ""); int age = ("age", 0); boolean married = ("married", false); ("MainActivity", "name is " + name); ("MainActivity", "age is " + age); ("MainActivity", "married is " + married); } }); } }
You can see that we first pass the click event of the restore data buttongetSharedPreferences()The method is obtainedSharedPreferencesand then call itsgetString()、getInt()andgetBoolean()The method obtains the name, age and whether you are married. If the corresponding value is not found, the default value passed in the method will be used instead, and finally print these values through Log.
With this simple example, we understand how to implement data storage using SharedPreferences. In contrast, SharedPreferences storage is indeed much simpler and more convenient than text storage, and has a lot more application scenarios. For example, the preference setting function in many applications actually uses SharedPreferences technology.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.