数据存储——四种存储方式——共享参数SharedPreferences——保存路径是:/data/data/应用包名/shared_prefs/文件名.xml
共享参数的用法
SharedPreferences是Android的一个轻量级存储工具,采用的存储结构是Key-Value的键值对方式。
共享参数的存储介质是符合XML规范的配置文件。保存路径是:/data/data/应用包名/shared_prefs/文件名.xml
下面是一个共享参数的XML文件示例:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="name">Mr Lee</string> <int name="age" value="30" /> <boolean name="married" value="true" /> <float name="weight" value="100.0" /> </map>
// 从share.xml中获取共享参数对象 SharedPreferences shared = getSharedPreferences("share", MODE_PRIVATE); // 下面是写入共享参数的代码例子 SharedPreferences.Editor editor = shared.edit(); // 获得编辑器的对象 editor.putString("name", "Mr Lee"); // 添加一个名叫name的字符串参数 editor.putInt("age", 30); // 添加一个名叫age的整型参数 editor.putBoolean("married", true); // 添加一个名叫married的布尔型参数 editor.putFloat("weight", 100f); // 添加一个名叫weight的浮点数参数 editor.commit(); // 提交编辑器中的修改 // 下面是读取共享参数的代码例子 String name = shared.getString("name", ""); // 从共享参数中获得名叫name的字符串 int age = shared.getInt("age", 0); // 从共享参数中获得名叫age的整型数 boolean married = shared.getBoolean("married", false); // 从共享参数中获得名叫married的布尔数 float weight = shared.getFloat("weight", 0); // 从共享参数中获得名叫weight的浮点数
==========================================================================================
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp" > <RelativeLayout android:layout_width="match_parent" android:layout_height="40dp" > <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="match_parent" 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="3dp" android:layout_marginTop="3dp" 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:textSize="17sp" /> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="40dp" > <TextView android:id="@+id/tv_age" android:layout_width="wrap_content" android:layout_height="match_parent" 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="3dp" android:layout_marginTop="3dp" 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:textSize="17sp" /> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="40dp" > <TextView android:id="@+id/tv_height" android:layout_width="wrap_content" android:layout_height="match_parent" 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="3dp" android:layout_marginTop="3dp" 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:textSize="17sp" /> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="40dp" > <TextView android:id="@+id/tv_weight" android:layout_width="wrap_content" android:layout_height="match_parent" 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="3dp" android:layout_marginTop="3dp" 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:textSize="17sp" /> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="40dp" > <CheckBox android:id="@+id/ck_married" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center" android:checked="false" android:text="已婚" android:textColor="@color/black" android:textSize="17sp" /> </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="17sp" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@drawable/shape_edit_focus"/> <item android:drawable="@drawable/shape_edit_normal"/> </selector>
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <!-- 指定了形状内部的填充颜色 --> <solid android:color="#ffffff" /> <!-- 指定了形状轮廓的粗细与颜色 --> <stroke android:width="1dp" android:color="#aaaaaa" /> <!-- 指定了形状四个圆角的半径 --> <corners android:radius="5dp" /> <!-- 指定了形状四个方向的间距 --> <padding android:bottom="2dp" android:left="2dp" android:right="2dp" android:top="2dp" /> </shape>
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <!-- 指定了形状内部的填充颜色 --> <solid android:color="#ffffff" /> <!-- 指定了形状轮廓的粗细与颜色 --> <stroke android:width="1dp" android:color="#0000ff" /> <!-- 指定了形状四个圆角的半径 --> <corners android:radius="5dp" /> <!-- 指定了形状四个方向的间距 --> <padding android:bottom="2dp" android:left="2dp" android:right="2dp" android:top="2dp" /> </shape>
package com.example.myapplication; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; public class MainActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { private SharedPreferences mShared; // 声明一个共享参数对象 private EditText et_name; private EditText et_age; private EditText et_height; private EditText et_weight; private boolean isMarried = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_name = findViewById(R.id.et_name); et_age = findViewById(R.id.et_age); et_height = findViewById(R.id.et_height); et_weight = findViewById(R.id.et_weight); CheckBox ck_married = findViewById(R.id.ck_married); ck_married.setOnCheckedChangeListener(this); findViewById(R.id.btn_save).setOnClickListener(this); // 从share.xml中获取共享参数对象 mShared = getSharedPreferences("share", MODE_PRIVATE); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { isMarried = isChecked; } @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 (TextUtils.isEmpty(name)) { ToastUtil.show(this, "请先填写姓名"); return; } else if (TextUtils.isEmpty(age)) { ToastUtil.show(this, "请先填写年龄"); return; } else if (TextUtils.isEmpty(height)) { ToastUtil.show(this, "请先填写身高"); return; } else if (TextUtils.isEmpty(weight)) { ToastUtil.show(this, "请先填写体重"); return; } SharedPreferences.Editor editor = mShared.edit(); // 获得编辑器的对象 editor.putString("name", name); // 添加一个名叫name的字符串参数 editor.putInt("age", Integer.parseInt(age)); // 添加一个名叫age的整型参数 editor.putLong("height", Long.parseLong(height)); // 添加一个名叫height的长整型参数 editor.putFloat("weight", Float.parseFloat(weight)); // 添加一个名叫weight的浮点数参数 editor.putBoolean("married", isMarried); // 添加一个名叫married的布尔型参数 editor.putString("update_time", DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss")); editor.commit(); // 提交编辑器中的修改 ToastUtil.show(this, "数据已写入共享参数"); } } }
package com.example.myapplication; import android.content.Context; import android.widget.Toast; public class ToastUtil { public static void show(Context ctx, String desc) { Toast.makeText(ctx, desc, Toast.LENGTH_SHORT).show(); } }
=========================================================================================
之前保持的数据:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="update_time">20220710152200</string> <string name="name">王12正国</string> <float name="weight" value="21.86" /> <boolean name="married" value="true" /> <int name="age" value="32" /> <long name="height" value="178" /> </map>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp" > <TextView android:id="@+id/tv_share" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="17sp" /> </LinearLayout>
package com.example.myapplication; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.Map; public class MainActivity extends AppCompatActivity { private TextView tv_share; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_share = findViewById(R.id.tv_share); readSharedPreferences(); // 从共享参数中读取信息 } // 从共享参数中读取信息 private void readSharedPreferences() { // 从share.xml中获取共享参数对象 SharedPreferences shared = getSharedPreferences("share", MODE_PRIVATE); String desc = "共享参数中保存的信息如下:"; // 获取共享参数保存的所有映射配对信息 Map<String, Object> mapParam = (Map<String, Object>) shared.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, shared.getString(key, "")); } else if (value instanceof Integer) { // 如果配对值的类型为整型数 desc = String.format("%s\n %s的取值为%d", desc, key, shared.getInt(key, 0)); } else if (value instanceof Float) { // 如果配对值的类型为浮点数 desc = String.format("%s\n %s的取值为%f", desc, key, shared.getFloat(key, 0.0f)); } else if (value instanceof Boolean) { // 如果配对值的类型为布尔数 desc = String.format("%s\n %s的取值为%b", desc, key, shared.getBoolean(key, false)); } else if (value instanceof Long) { // 如果配对值的类型为长整型 desc = String.format("%s\n %s的取值为%d", desc, key, shared.getLong(key, 0L)); } else { // 如果配对值的类型为未知类型 desc = String.format("%s\n参数%s的取值为未知类型", desc, key); } } if (mapParam.size() <= 0) { desc = "共享参数中保存的信息为空"; } tv_share.setText(desc); } }
==============================================================================================