【Android】数据存储-SharedPreferences

1、SharedPreferences

是什么?
一种数据持久化的方法
共享配置数据

用在哪?
保存一些简单数据,key-value
只需一次登录,下次自动登录

存在哪?
data/data/包名/shared_prefs
这是内部存储

2、使用方法

常量定义:

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 保存

系统会自动帮我们创建一个xml文件,名字是:preference_name, 地址: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的区别
    }

生成的preference_name.xml内容:

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

2-2 读取

如果能读到键LIST_VIEW_DATA_COUNTS对应的值,就用读到的值;如果读不到,就用默认值DEFAULT_VALUE

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

2-3 修改

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

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

当内容发生改变时的监听器,会告诉我们是哪个key发生了改变:

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

2-4 删除

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

3、其他注意点

3-1 apply和commit区别

和网络相关的,和IO相关的,都要另开线程去完成,用异步的方式。

apply 后台写入,另开线程写;返回void。
commit 立即写入,用UI线程写;返回bool值

3-2 清除数据

先安装ADB IDEA插件,file——》Settings——》Plugin——》搜索并安装,安装后重启AS

用adb命令去清除数据

猜你喜欢

转载自blog.csdn.net/qq_30885821/article/details/108895536