[Android] Data storage-SharedPreferences

1、SharedPreferences

What is it?
A method of data persistence to
share configuration data

Where is it used?
Save some simple data, key-value
only needs to log in once, and log in automatically next time

Where does it exist?
data/data/package name/shared_prefs
This is internal storage

2. How to use

Constant definition:

Key  		public static final String LIST_VIEW_DATA_COUNTS = "list_view_data_counts";
文件名称	    public static final String PREFERENCE_NAME = "preference_name";
默认值	    public static final int DEFAULT_VALUE = 10;

2-1 Save

The system will automatically create an xml file for us, the name is: preference_name, address: data/data/com.jsc4.aboutactivity

    private void saveData2Preference() {
    
    
        SharedPreferences sharedPreferences = ListViewDemoActivity.this.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(LIST_VIEW_DATA_COUNTS, mDataCounts);
        editor.apply();		注意与commit的区别
    }

The generated preference_name.xml content:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <int name="list_view_data_counts" value="16" />
</map>

2-2 Read

If you can read the value corresponding to the key LIST_VIEW_DATA_COUNTS, use the read value; if you can't read it, use the default value DEFAULT_VALUE

SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
mDataCounts = sharedPreferences.getInt(LIST_VIEW_DATA_COUNTS, DEFAULT_VALUE);

2-3 Modification

editor.putInt("list_view_data_counts", mDataCounts); 这里mDataCounts就是要存起来的数字

传入不同的值,就是修改:
editor.putInt("list_view_data_counts", mDataCounts + 1); 这里mDataCounts就是要存起来的数字
editor.apply();	提交修改

When the content changes, the listener will tell us which key has changed:

sharedPreferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
    
    
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    
    
        
    }
});

2-4 delete

editor.remove(LIST_VIEW_DATA_COUNTS);
editor.apply();	提交修改

3. Other points of attention

3-1 difference between apply and commit

For network-related and IO-related, separate threads must be opened to complete, asynchronously.

apply Write in the background, and open another thread to write; return void.
commit writes immediately and writes with UI thread; returns bool value

3-2 Clear data

Install ADB IDEA plug-in first, file——"Settings——"Plugin——"search and install, restart AS after installation

Use adb command to clear data

Guess you like

Origin blog.csdn.net/qq_30885821/article/details/108895536