【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命令去清除数据

3-3 一个工程中只能有一个sharedPreferences对象!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值