1.2 SharedPreference 的使用技巧

点此进入:从零快速构建APP系列目录导图
点此进入:UI编程系列目录导图
点此进入:四大组件系列目录导图
点此进入:数据网络和线程系列目录导图

不同于文件的存储方式, SharedPreferences 是使用键值对的方式来存储数据的。也就是说当保存一条数据的时候,需要给这条数据提供一个对应的键,这样在读取数据的时候就可以通过这个键把相应的值取出来。而且 SharedPreferences 还支持多种不同的数据类型存储,如果存储的数据类型是整型,那么读取出来的数据也是整型的,存储的数据是一个字符串,读取出来的数据仍然是字符串。所以一般来讲使用 SharedPreferences 来进行数据持久化要比使用文件方便很多,下面我们来看一下它的具体用法。

本节例程下载地址:WillFlowSharedPreference

一、将数据存储到 SharedPreferences 中

要想使用 SharedPreferences 来存储数据,首先需要获取到 SharedPreferences 对象。Android 中主要提供了三种方法用于得到 SharedPreferences 对象。

(1)Context 类中的 getSharedPreferences() 方法

此方法接收两个参数,第一个参数用于指定 SharedPreferences 文件的名称,如果指定的文件不存在则会创建一个, SharedPreferences 文件都是存放在 /data/data//shared_prefs/ 目录下的。第二个参数用于指定操作模式,主要有两种模式可以选择, MODE_PRIVATE 和 MODE_MULTI_PROCESS。 MODE_PRIVATE 仍然是默认的操作模式,和直接传入 0 效果是相同的,表示只有当前的应用程序才可以对这个 SharedPreferences 文件进行读写。MODE_MULTI_PROCESS 则一般是用于会有多个进程中对同一个 SharedPreferences 文件进行读写的情况。另外两种 MODE_WORLD_READABLE 和 MODE_WORLD_WRITEABLE 这两种模式已在 Android 4.2 版本中被废弃。

(2)Activity 类中的 getPreferences() 方法

这个方法和 Context 中的 getSharedPreferences()方法很相似,不过它只接收一个操作模式参数,因为使用这个方法时会自动将当前活动的类名作为 SharedPreferences 的文件名。

(3)PreferenceManager 类中的 getDefaultSharedPreferences() 方法

这是一个静态方法,它接收一个 Context 参数,并自动使用当前应用程序的包名作为前缀来命名 SharedPreferences 文件。

得到了 SharedPreferences 对象之后,就可以开始向 SharedPreferences 文件中存储数据了,主要可以分为三步实现:
- 调用 SharedPreferences 对象的 edit() 方法来获取一个 SharedPreferences.Editor 对象。
- 向 SharedPreferences.Editor 对象中添加数据,比如添加一个布尔型数据就使用 putBoolean 方法,添加一个字符串则使用 putString() 方法,以此类推。
- 调用 commit() 方法将添加的数据提交,从而完成数据存储操作。

接下来通过一个例子来体验一下 SharedPreferences 存储的用法。

修改 activity_main.xml 中的代码,如下所示:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.wgh.willflowsharedpreference.MainActivity">

    <Button
        android:id="@+id/button_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存数据"
        android:textColor="#03a1fc"
        android:textSize="25dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
然后修改 MainActivity 中的代码,如下所示:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButton = (Button) findViewById(R.id.button_save);
        mButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_save:
                SharedPreferences.Editor editor = getSharedPreferences("dataSP", MODE_PRIVATE).edit();
                editor.putString("name", "WillFlow");
                editor.putInt("age", 18);
                editor.putBoolean("married", false);
                editor.apply();
                break;
        }
    }
}

这里首先给按钮注册了一个点击事件,然后在点击事件中通过 getSharedPreferences() 方法指定 SharedPreferences 的文件名为dataSP,并得到了 SharedPreferences.Editor 对象。接着向这个对象中添加了三条不同类型的数据,最后调用 apply() 方法进行提交,从而完成了数据存储的操作。

编译运行并到后台查看数据:

可以看到,根据我们白色框内部的命令以及红色框内部的文本内容显示,我们刚刚在按钮的点击事件中添加的所有数据都已经成功保存下来了,并且 SharedPreferences 文件是使用 XML 格式来对数据进行管理的。

二、从 SharedPreferences 中读取数据

SharedPreferences 对象中提供了一系列的 get 方法用于对存储的数据进行读取,每种 get 方法都对应了SharedPreferences.Editor 中的一种 put 方法,比如读取一个布尔型数据就使用 getBoolean( )方法,读取一个字符串就使用 getString() 方法。这些 get 方法都接收两个参数,第一个参数是键,传入存储数据时使用的键就可以得到相应的值了,第二个参数是默认值,即表示当传入的键找不到对应的值时,会以什么样的默认值进行返回。

修改 activity_main.xml 中的代码,如下所示:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.wgh.willflowsharedpreference.MainActivity">

    ......

    <Button
        android:id="@+id/button_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="读取数据"
        android:textColor="#05d705"
        android:textSize="25dp" />

</android.support.constraint.ConstraintLayout>

这里增加了一个读取数据的按钮,我们希望通过点击这个按钮来从 SharedPreferences 文件中读取数据。

修改 MainActivity 中的代码,如下所示:
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            ......
            case R.id.button_read:
                SharedPreferences pref = getSharedPreferences("dataSP", MODE_PRIVATE);
                String name = pref.getString("name", "");
                int age = pref.getInt("age", 0);
                boolean married = pref.getBoolean("married", false);
                Log.i(TAG, "name : " + name + ", age : " + age + ", married : " + married);
                break;
        }
    }

我们在还原数据按钮的点击事件中首先通过 getSharedPreferences() 方法得到了 SharedPreferences 对象,然后分别调用它的 getString()、 getInt() 和 getBoolean() 方法去获取前面所存储的姓名、年龄和是否已婚,如果没有找到相应的值就会使用方法中传入的默认值来代替,最后通过 Log 将这些值打印出来。

编译运行,查看 Log 输出:

三、工具类

每次都要自行实例化 SharedPreference 相关的类肯定很麻烦,这里贴个 SharedPreference 的工具类,大家可以贴到自己的项目中方便使用:

/**
 * Created by   : WGH.
 */
public class SPUtil {

    /**
     * 保存在手机里的SP文件名
     */
    private static final String FILE_NAME = "SPU_WILL_FLOW";

    /**
     * 保存数据
     */
    public static void put(Context context, String key, Object obj) {
        if (null == context) {
            context = MyApplication.context();
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (obj instanceof Boolean) {
            editor.putBoolean(key, (Boolean) obj);
        } else if (obj instanceof Float) {
            editor.putFloat(key, (Float) obj);
        } else if (obj instanceof Integer) {
            editor.putInt(key, (Integer) obj);
        } else if (obj instanceof Long) {
            editor.putLong(key, (Long) obj);
        } else {
            editor.putString(key, (String) obj);
        }
        editor.apply();
    }

    public static void put(String key, Object object) {
        put(MyApplication.context(), key, object);
    }


    /**
     * 获取指定数据
     */
    public static Object get(Context context, String key, Object defaultObj) {
        if (null == context) {
            context = MyApplication.context();
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        if (defaultObj instanceof Boolean) {
            return sharedPreferences.getBoolean(key, (Boolean) defaultObj);
        } else if (defaultObj instanceof Float) {
            return sharedPreferences.getFloat(key, (Float) defaultObj);
        } else if (defaultObj instanceof Integer) {
            return sharedPreferences.getInt(key, (Integer) defaultObj);
        } else if (defaultObj instanceof Long) {
            return sharedPreferences.getLong(key, (Long) defaultObj);
        } else if (defaultObj instanceof String) {
            return sharedPreferences.getString(key, (String) defaultObj);
        }
        return null;
    }

    public static Object get(String key, Object object) {
        return get(MyApplication.context(), key, object);
    }

    /**
     * 删除指定数据
     */
    public static void remove(Context context, String key) {
        if (null == context) {
            context = MyApplication.context();
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(key);
        editor.apply();
    }

    public static void remove(String key) {
        remove(MyApplication.context(), key);
    }


    /**
     * 返回所有键值对
     */
    public static Map<String, ?> getAll(Context context) {
        if (null == context) {
            context = MyApplication.context();
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        Map<String, ?> map = sharedPreferences.getAll();
        return map;
    }

    public static Map<String, ?> getAll() {
        return getAll(MyApplication.context());
    }

    /**
     * 删除所有数据
     */
    public static void clear(Context context) {
        if (null == context) {
            context = MyApplication.context();
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }

    public static void clear() {
        clear(MyApplication.context());
    }

    /**
     * 检查key对应的数据是否存在
     */
    public static boolean contains(Context context, String key) {
        if (null == context) {
            context = MyApplication.context();
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.contains(key);
    }

    public static boolean contains(String key) {
        return contains(MyApplication.context(), key);
    }
}

点此进入:GitHub开源项目“爱阅”。“爱阅”专注于收集优质的文章、站点、教程,与大家共分享。下面是“爱阅”的效果图:


联系方式:

简书:WillFlow
CSDN:WillFlow
微信公众号:WillFlow

微信公众号:WillFlow

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值