• 【Android -- 数据存储】使用 SharedPreferences 存储数据


    在这里插入图片描述

    一、前言

    在 Android 中一共提供了五种数据存储方式,分别为:
    1. Files:通过FileInputStream和FileOutputStream对文件进行操作。具体使用方法可以参阅博文《Android学习笔记34:使用文件存储数据》。

    2. Shared Preferences:常用来存储键值对形式的数据,对系统配置信息进行保存。

    3. Content Providers:数据共享,用于应用程序之间数据的访问。

    4. SQLite:Android自带的轻量级关系型数据库,支持SQL语言,用来存储大量的数据,并且能够对数据进行使用、更新、维护等操作。

    5. Network:通过网络来存储和获取数据。

    本篇博文主要介绍第二种方式,通过 Shared Preferences 存储数据。

    二、获取 SharedPreferences

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

    1. Context 类中的 getSharedPreferences()方法:
    此方法接收两个参数,第一个参数用于指定 SharedPreferences 文件的名称,如果指定的文件不存在则会创建一个,第二个参数用于指定操作模式,主要有以下几种模式可以选择。MODE_PRIVATE 是默认的操作模式,和直接传入 0 效果是相同的。
    MODE_WORLD_READABLE 和 MODE_WORLD_WRITEABLE 这两种模式已在 Android 4.2 版本中被废弃。

    • Context.MODE_PRIVATE: 指定该 SharedPreferences 数据只能被本应用程序读、写;
    • Context.MODE_WORLD_READABLE: 指定该 SharedPreferences 数据能被其他应用程序读,但不能写;
    • Context.MODE_WORLD_WRITEABLE: 指定该 SharedPreferences 数据能被其他应用程序读;
    • Context.MODE_APPEND:该模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件;

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

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

    三、SharedPreferences 的使用

    SharedPreferences 对象本身只能获取数据而不支持存储和修改,存储修改是通过 SharedPreferences.edit() 获取的内部接口 Editor 对象实现。使用 Preference 来存取数据,用到了 SharedPreferences 接口和 SharedPreferences 的一个内部接口 SharedPreferences.Editor ,这两个接口在 android.content 包中;

    1)写入数据:
         //步骤1:创建一个SharedPreferences对象
         SharedPreferences sharedPreferences= getSharedPreferences("data",Context.MODE_PRIVATE);
         //步骤2: 实例化SharedPreferences.Editor对象
         SharedPreferences.Editor editor = sharedPreferences.edit();
         //步骤3:将获取过来的值放入文件
         editor.putString("name",Tom);
         editor.putInt("age", 28);
         editor.putBoolean("marrid",false);
         //步骤4:提交               
         editor.commit();
    
    
     2)读取数据:
         SharedPreferences sharedPreferences= getSharedPreferences("data", Context .MODE_PRIVATE);
         String userId=sharedPreferences.getString("name","");
      
    3)删除指定数据
         editor.remove("name");
         editor.commit();
    
    
    4)清空数据
         editor.clear();
         editor.commit();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    注意:如果在 Fragment 中使用 SharedPreferences 时,需要放在 onAttach(Activity activity) 里面进行 SharedPreferences 的初始化,否则会报空指针 即 getActivity()会可能返回null !

    读写其他应用的 SharedPreferences 步骤如下:
     1. 在创建 SharedPreferences 时,指定 MODE_WORLD_READABLE 模式,表明该 SharedPreferences 数据可以被其他程序读取;
     2. 创建其他应用程序对应的 Context;
     3. 使用其他程序的 Context 获取对应的 SharedPreferences ;
     4. 如果是写入数据,使用 Editor 接口即可,所有其他操作均和前面一致;

    try {
    //这里的com.example.mpreferences 就是应用的包名
     Context mcontext = createPackageContext("com.example.mpreferences", CONTEXT_IGNORE_SECURITY);
    
    
     SharedPreferences msharedpreferences = mcontext.getSharedPreferences("name_preference", MODE_PRIVATE);
     int count = msharedpreferences.getInt("count", 0);
    
    
     } catch (PackageManager.NameNotFoundException e) {
           e.printStackTrace();
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    四、工具类 PreferencesUtils.java

    public class PreferencesUtils{
        public static String PREFERENCE_NAME = "ScarfAndroidCommon";
    
        private PreferencesUtils() {
            throw new AssertionError();
        }
    
        // put string preferences
        public static boolean putString(Context context, String key, String value) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString(key, value);
            return editor.commit();
        }
    
        // get string preferences
        public static String getString(Context context, String key) {
            return getString(context, key, null);
        }
    
        // get string preferences
        public static String getString(Context context, String key, String defaultValue) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            return settings.getString(key, defaultValue);
        }
    
        // put int preferences
        public static boolean putInt(Context context, String key, int value) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            editor.putInt(key, value);
            return editor.commit();
        }
    
        // get int preferences
        public static int getInt(Context context, String key) {
            return getInt(context, key, -1);
        }
    
        // get int preferences
        public static int getInt(Context context, String key, int defaultValue) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            return settings.getInt(key, defaultValue);
        }
    
        // put long preferences
        public static boolean putLong(Context context, String key, long value) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            editor.putLong(key, value);
            return editor.commit();
        }
    
        // get long preferences
        public static long getLong(Context context, String key) {
            return getLong(context, key, -1);
        }
    
        // get long preferences
        public static long getLong(Context context, String key, long defaultValue) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            return settings.getLong(key, defaultValue);
        }
    
        // put float preferences
        public static boolean putFloat(Context context, String key, float value) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            editor.putFloat(key, value);
            return editor.commit();
        }
    
        // get float preferences
        public static float getFloat(Context context, String key) {
            return getFloat(context, key, -1);
        }
    
        // get float preferences
        public static float getFloat(Context context, String key, float defaultValue) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            return settings.getFloat(key, defaultValue);
        }
    
        // put boolean preferences
        public static boolean putBoolean(Context context, String key, boolean value) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean(key, value);
            return editor.commit();
        }
    
        // get boolean preferences, default is false
        public static boolean getBoolean(Context context, String key) {
            return getBoolean(context, key, false);
        }
    
        // get boolean preferences
        public static boolean getBoolean(Context context, String key, boolean defaultValue) {
            SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            return settings.getBoolean(key, defaultValue);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
  • 相关阅读:
    操作系统MIT6.S081:Lab4->Trap
    云计算-Linux文件类型介绍,归属关系,基本权限介绍
    008 OpenCV matchTemplate 模板匹配
    8.SpringBoot 与消息
    Kotlin基础入门 - 从Java快速过度Kotlin
    面向对象的五大基本原则
    CAS:851113-28-5 (生物素-ahx-ahx-酪胺)
    Dockerfile 镜像创建
    Go用两个协程交替打印100以内的奇偶数
    JS高阶:深入理解数据、变量、内存
  • 原文地址:https://blog.csdn.net/duoduo_11011/article/details/124587943