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();
            }
        });
Top
收藏
关注
评论
原文地址:https://www.cnblogs.com/Joy-et/p/5240704.html