• Android——共享参数SharedPreferences


    4数据存储

    共享参数SharedPreferences、数据库SQLite、SD卡文件、App的全局内存

    4.1共享参数SharedPreferences

    SharedPreferences是一个轻量级存储工具,采用的存储结构时Key-Value的键值对方式

    SharedPreferences的存储介质是符合XML规范的配置文件。

    保存SharedPreferences键值对信息的文件路径时/data/data/应用包名/shared_prefs/文件名.xml

    
    <map>
    	<string name="name">string>
      <int name="age" value="30"/>
      <boolean name="married" value="true"/>
      <float name="weight" value="100.0"/>
    map>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    ​ 基于XML格式的特点,SharedPreferences主要适用于如下场合:

    1. 简单且孤立的数据。若是复杂且相互间有关的数据,则要保存在数据库中。
    2. 文本形式的数据。若是二进制数据,则要保存在文件中。
    3. 需要持久化存储的数据。在App退出后再次启动时,之前保存的数据仍然有效。

    实际开发中,共享参数经常存储的数据有App的个性化配置信息、用户使用App的行为信息、临时需要保存的片段信息等

    SharedPreferences对数据的存储和读取操作类似于Map,也有put函数用于存储数据、get函数用于读取数据。在使用共享参数之前,要先调用getSharedPreferences函数声明文件名与操作模式:

    SharedPreferences mShared = getSharedPreferences("share", MODE_PRIVATE);
    
    • 1

    getSharedPreferences方法的第一个参数是文件名,上面的share表示当前使用的共享参数文件名是share.xml;第二个参数是操作模式,一般都填MODE_PRIVATE,表示私有模式。

    共享参数存储数据要借助于Editor类:

    SharedPreferences.Editor editor = shared.edit();// 获得编辑器的对象
    editor.putString("name","Mr Lee");// 添加一个名叫name的字符串参数
    editor.putInt("age",23);// 添加一个名叫age的整形参数
    editor.putBoolean("married",true);// 添加一个名叫married的布尔型参数
    editor.putFloat("weight",100f);// 添加一个名叫weight的浮点数参数
    editor.commit();// 提交编辑器中的修改
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    共享参数读取数据相对简单,直接使用对象即可完成数据读取方法的调用,注意get方法的第二个参数表示默认值:

    String name = shared.getString("name","");// 从共享参数中获得名叫name的字符串
    int age = shared.getInt("age",0);// 从共享参数中获得名叫age的整形数
    boolean married = getBoolean("married",false);// 从共享参数中获得名叫married的布尔数
    float weight = getFloat("weight",0);// 从共享参数中获得名叫weight的浮点数
    
    • 1
    • 2
    • 3
    • 4

    Write:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:orientation="vertical"
        android:padding="10dp" >
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp" >
    
            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:gravity="center"
                android:text="姓名:"
                android:textColor="@color/black"
                android:textSize="17sp" />
    
            <EditText
                android:id="@+id/et_name"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="5dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@+id/tv_name"
                android:background="@drawable/editext_selector"
                android:gravity="left|center"
                android:hint="请输入姓名"
                android:inputType="text"
                android:maxLength="12"
                android:textColor="@color/black"
                android:textColorHint="@color/grey"
                android:textCursorDrawable="@drawable/text_cursor"
                android:textSize="17sp" />
        RelativeLayout>
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp" >
    
            <TextView
                android:id="@+id/tv_age"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:gravity="center"
                android:text="年龄:"
                android:textColor="@color/black"
                android:textSize="17sp" />
    
            <EditText
                android:id="@+id/et_age"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="5dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@+id/tv_age"
                android:background="@drawable/editext_selector"
                android:gravity="left|center"
                android:hint="请输入年龄"
                android:inputType="number"
                android:maxLength="2"
                android:textColor="@color/black"
                android:textColorHint="@color/grey"
                android:textCursorDrawable="@drawable/text_cursor"
                android:textSize="17sp" />
        RelativeLayout>
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp" >
    
            <TextView
                android:id="@+id/tv_height"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:gravity="center"
                android:text="身高:"
                android:textColor="@color/black"
                android:textSize="17sp" />
    
            <EditText
                android:id="@+id/et_height"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="5dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@+id/tv_height"
                android:background="@drawable/editext_selector"
                android:gravity="left|center"
                android:hint="请输入身高"
                android:inputType="number"
                android:maxLength="3"
                android:textColor="@color/black"
                android:textColorHint="@color/grey"
                android:textCursorDrawable="@drawable/text_cursor"
                android:textSize="17sp" />
        RelativeLayout>
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp" >
    
            <TextView
                android:id="@+id/tv_weight"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:gravity="center"
                android:text="体重:"
                android:textColor="@color/black"
                android:textSize="17sp" />
    
            <EditText
                android:id="@+id/et_weight"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="5dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@+id/tv_weight"
                android:background="@drawable/editext_selector"
                android:gravity="left|center"
                android:hint="请输入体重"
                android:inputType="numberDecimal"
                android:maxLength="5"
                android:textColor="@color/black"
                android:textColorHint="@color/grey"
                android:textCursorDrawable="@drawable/text_cursor"
                android:textSize="17sp" />
        RelativeLayout>
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp" >
    
            <TextView
                android:id="@+id/tv_married"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:gravity="center"
                android:text="婚否:"
                android:textColor="@color/black"
                android:textSize="17sp" />
    
            <Spinner
                android:id="@+id/sp_married"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_toRightOf="@+id/tv_married"
                android:gravity="left|center"
                android:spinnerMode="dialog" />
        RelativeLayout>
    
        <Button
            android:id="@+id/btn_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="保存到共享参数"
            android:textColor="@color/black"
            android:textSize="20sp" />
    
    LinearLayout>
    
    • 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
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    public class ShareWriteActivity extends AppCompatActivity implements View.OnClickListener {
    
        private SharedPreferences mShared;
        private EditText et_name;
        private EditText et_age;
        private EditText et_height;
        private EditText et_weight;
        private boolean bMarried = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_share_write);
            et_name = (EditText) findViewById(R.id.et_name);
            et_age = (EditText) findViewById(R.id.et_age);
            et_height = (EditText) findViewById(R.id.et_height);
            et_weight = (EditText) findViewById(R.id.et_weight);
            findViewById(R.id.btn_save).setOnClickListener(this);
    
            ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
                    R.layout.item_select, typeArray);
            typeAdapter.setDropDownViewResource(R.layout.item_dropdown);
            Spinner sp_married = (Spinner) findViewById(R.id.sp_married);
            sp_married.setPrompt("请选择婚姻状况");
            sp_married.setAdapter(typeAdapter);
            sp_married.setSelection(0);
            sp_married.setOnItemSelectedListener(new TypeSelectedListener());
    
            mShared = getSharedPreferences("share", MODE_PRIVATE);
        }
    
        private String[] typeArray = {"未婚", "已婚"};
        class TypeSelectedListener implements AdapterView.OnItemSelectedListener {
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                bMarried = (arg2==0)?false:true;
            }
    
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        }
    
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btn_save) {
                String name = et_name.getText().toString();
                String age = et_age.getText().toString();
                String height = et_height.getText().toString();
                String weight = et_weight.getText().toString();
                if (name==null || name.length()<=0) {
                    showToast("请先填写姓名");
                    return;
                }
                if (age==null || age.length()<=0) {
                    showToast("请先填写年龄");
                    return;
                }
                if (height==null || height.length()<=0) {
                    showToast("请先填写身高");
                    return;
                }
                if (weight==null || weight.length()<=0) {
                    showToast("请先填写体重");
                    return;
                }
    
                SharedPreferences.Editor editor = mShared.edit();
                editor.putString("name", name);
                editor.putInt("age", Integer.parseInt(age));
                editor.putLong("height", Long.parseLong(height));
                editor.putFloat("weight", Float.parseFloat(weight));
                editor.putBoolean("married", bMarried);
                editor.putString("update_time", DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss"));
                editor.commit();
                showToast("数据已写入共享参数");
            }
        }
    
        private void showToast(String desc) {
            Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
        }
    
    }
    
    • 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

    Read:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:orientation="vertical"
        android:padding="10dp" >
    
        <TextView
            android:id="@+id/tv_share"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="17sp" />
    
    LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    public class ShareReadActivity extends AppCompatActivity {
    
        private SharedPreferences mShared;
        private TextView tv_share;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_share_read);
            tv_share = (TextView) findViewById(R.id.tv_share);
            readSharedPreferences();
        }
    
        private void readSharedPreferences() {
            SharedPreferences mShared = getSharedPreferences("share", MODE_PRIVATE);
            String desc = "共享参数中保存的信息如下:";
            Map<String, Object> mapParam = (Map<String, Object>) mShared.getAll();
            for (Map.Entry<String, Object> item_map : mapParam.entrySet()) {
                String key = item_map.getKey();
                Object value = item_map.getValue();
                if (value instanceof String) {
                    desc = String.format("%s\n %s的取值为%s", desc, key,
                            mShared.getString(key, ""));
                } else if (value instanceof Integer) {
                    desc = String.format("%s\n %s的取值为%d", desc, key,
                            mShared.getInt(key, 0));
                } else if (value instanceof Float) {
                    desc = String.format("%s\n %s的取值为%f", desc, key,
                            mShared.getFloat(key, 0.0f));
                } else if (value instanceof Boolean) {
                    desc = String.format("%s\n %s的取值为%b", desc, key,
                            mShared.getBoolean(key, false));
                } else if (value instanceof Long) {
                    desc = String.format("%s\n %s的取值为%d", desc, key,
                            mShared.getLong(key, 0l));
                } else {
                    desc = String.format("%s\n参数%s的取值为未知类型", desc, key);
                }
            }
            if (mapParam==null || mapParam.size()<=0) {
                desc = "共享参数中保存的信息为空";
            }
            tv_share.setText(desc);
        }
    
    }
    
    • 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
  • 相关阅读:
    Docker-概念及配置(超详细)
    【TensorFlow】TensorFlow中的三种计算图
    python 科学计算三维可视化笔记(第二周 基础实战)
    CSAPP Lab4: Cache
    【JUC】交换器Exchanger详解
    MATLAB2016笔记(二):基本矩阵操作
    【FPGA创新设计竞赛——2022紫光同创杯】1、“基于 RISC-V 处理器的软硬件系统设计”赛题介绍
    二叉树简介
    重写muduo网络库开发环境和前期准备
    docker常用命令二
  • 原文地址:https://blog.csdn.net/weixin_45688141/article/details/126324544