安卓基础之《(11)—数据存储(1)共享参数SharedPreferences》

一、共享参数的用法

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

2、共享参数的存储介质是符合XML规范的配置文件。保存路径是:/data/data/应用包名/shared_prefs/文件名.xml

3、共享参数的使用场景

(1)简单且孤立的数据。若是复杂且相互间有关的数据,则要保存在数据库中

(2)文本形式的数据。若是二进制数据,则要保存在文件中

(3)需要持久化存储的数据。在App退出后再次启动时,之前保存的数据仍然有效

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

5、例子:把注册信息写入共享参数

activity_share_write.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".ShareWriteActivity">

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="2"
        android:rowCount="4">

        <TextView
            android:layout_width="60dp"
            android:layout_height="wrap_content"
            android:text="姓名:"
            android:textSize="17sp"/>

        <EditText
            android:id="@+id/et_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_columnWeight="1"
            android:inputType="text"
            android:hint="请输入姓名"/>

        <TextView
            android:layout_width="60dp"
            android:layout_height="wrap_content"
            android:text="年龄:"
            android:textSize="17sp"/>

        <EditText
            android:id="@+id/et_age"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_columnWeight="1"
            android:inputType="number"
            android:maxLength="3"
            android:hint="请输入年龄"/>

        <TextView
            android:layout_width="60dp"
            android:layout_height="wrap_content"
            android:text="身高:"
            android:textSize="17sp"/>

        <EditText
            android:id="@+id/et_height"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_columnWeight="1"
            android:inputType="numberDecimal"
            android:maxLength="6"
            android:hint="请输入身高"/>

        <TextView
            android:layout_width="60dp"
            android:layout_height="wrap_content"
            android:text="体重:"
            android:textSize="17sp"/>

        <EditText
            android:id="@+id/et_weight"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_columnWeight="1"
            android:inputType="numberDecimal"
            android:maxLength="6"
            android:hint="请输入体重"/>

    </GridLayout>

    <CheckBox
        android:id="@+id/ck_married"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="已婚"
        android:textSize="17sp"/>

    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存到共享参数"
        android:textSize="17sp"/>

</LinearLayout>

ShareWriteActivity.java

java 复制代码
package com.example.chapter06;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import java.util.Map;

public class ShareWriteActivity extends AppCompatActivity {

    private EditText et_name;
    private EditText et_age;
    private EditText et_height;
    private EditText et_weight;
    private CheckBox ck_married;
    private SharedPreferences config;

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

        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);
        ck_married = findViewById(R.id.ck_married);

        config = getSharedPreferences("config", Context.MODE_PRIVATE);

        Button btn_save = findViewById(R.id.btn_save);
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = et_name.getText().toString();
                String age = et_age.getText().toString();
                String height = et_height.getText().toString();
                String weight = et_weight.getText().toString();

                // 获得编辑器
                SharedPreferences.Editor edit = config.edit();
                edit.putString("name", name);
                edit.putInt("age", Integer.parseInt(age));
                edit.putFloat("height", Float.parseFloat(height));
                edit.putFloat("weight", Float.parseFloat(weight));
                edit.putBoolean("married", ck_married.isChecked());
                // 提交
                edit.commit();
            }
        });

        // 读取文件,有的话就设置进去
        reload();
    }

    private void reload() {
        Map<String, ?> all = config.getAll();
        if (all.get("name") != null) {
            et_name.setText(String.valueOf(all.get("name")));
        }
        if (all.get("age") != null) {
            et_age.setText(String.valueOf(all.get("age")));
        }
        if (all.get("height") != null) {
            et_height.setText(String.valueOf(all.get("height")));
        }
        if (all.get("weight") != null) {
            et_weight.setText(String.valueOf(all.get("weight")));
        }
        if (all.get("married") != null) {
            ck_married.setChecked((boolean)all.get("married"));
        }
    }
}

生成的文件config.xml

XML 复制代码
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="name">qwer</string>
    <float name="weight" value="120.0" />
    <boolean name="married" value="true" />
    <int name="age" value="23" />
    <float name="height" value="170.5" />
</map>

reload()方法说明:读取文件,将保存的数据设置进页面

相关推荐
三少爷的鞋40 分钟前
不改变异步本质,只改变代码组织:Telegram 项目的 Kotlin 协程实践
android
好的佩奇10 小时前
蓝牙之广播与扫描
android·flutter·蓝牙
传奇开心果编程11 小时前
【Jetpack Compose娓娓道来】第36课:焦点管理与键盘输入——让遥控器、键盘和输入法都“找得到北”
android·kotlin·移动开发·交互·android jetpack·ui框架·声明式ui
hai_android12 小时前
AudioTrack 深度解析:从原理到实战
android·java·kotlin
红尘伴蝶舞12 小时前
从秒开优化到连环崩溃:深入剖析 ViewPager2 在常驻 DialogFragment 中的复用陷阱与自愈方案
android·kotlin
巫山老妖17 小时前
Android 应用架构演进:MVC / MVP / MVVM / MVI (2026)
android·android jetpack
木头左21 小时前
【架构设计】教育类 App 服务端化改造:AI 上移、题库分层与个人题库归属
android·架构设计·系统设计·后端开发·数据库设计
墨狂之逸才21 小时前
USB 的 HOST 和 DEVICE 到底有什么区别?ADB 调试应该选哪个?
android
奶油话梅糖1 天前
苹果的内核跑上了安卓手机:2,631 Star 的 HakiOS 让 XNU 在 Adreno GPU 上画出 118 帧
android·macos·智能手机
恋猫de小郭1 天前
Flutter THLC 的 WebView 滚动终于从 70 FPS 提升到 120 FPS
android·前端·flutter