Android之SharedPreferences数据存储

SharedPreference定义

SharedPreferences是Android平台中的一个轻量级的存储类,一般用于存储一些常用的配置,以键值对的方式进行存储,最终以xml的形式存储。存储位置为/data/data/<包名>/shared_prefs目录下。

 

使用

1、根据Context获取SharedPreferences对象;

2、通过SharedPreferences对象的edit()方法获取Editor对象;

3、通过Editor对象对SharedPreferences中的键值对进行编辑操作;

4、调用Editor的commit()方法提交编辑的数据;

5、通过SharedPreferences的getString,getInt等方法获取对应键的值。

示例代码

 btnCheckRunTimes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context=SpDataActivity.this;
                SharedPreferences sp=context.getSharedPreferences("spRuntimes",MODE_PRIVATE);
               int runtimes= sp.getInt("run_times",0);
                SharedPreferences.Editor editor=sp.edit();
                editor.putInt("run_times", runtimes + 1);
                editor.putString("user_name", "tim_et");
                editor.putBoolean("IsDt", true);
                editor.commit();

                String userName=sp.getString("user_name","Anonymous"); //获取user_name键对应的值,如果不存在user_name键则返回anonymous
                int times=sp.getInt("run_times", 0);
                boolean isDt=sp.getBoolean("IsDt",false);
                Toast.makeText(SpDataActivity.this,"user_name:"+userName+" run_times:"+times+" flag:"+String.valueOf(isDt),Toast.LENGTH_LONG).show();
            }
        });

 

转载于:https://www.cnblogs.com/Joy-et/p/5240704.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值