Android轻量级存储工具SharedPreferences的使用

1.简介

SharedPreferences是轻量级存储工具,采用的是Key-Value存储方式。一般用于存放App的个性化配置信息、临时保存的片段信息等。SharedPreferences存储键值信息是采用xml文件的形式,保存在/data/data/App包名/shared_prefs/文件名.xml(在安卓的Divice File Explorer栏可以轻易找到,如果创建时采用没有文件名的方法,那么这个xml文件会自动命名为当前activity的名称)。
例子图片

<!--例子中的存储键-值的xml文件-->
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="name">小明</string>
    <string name="hobby">唱 跳</string>
</map>

下面是使用SharedPreferences存入信息的核心代码及注释。

//第一个参数是文件名 第二个参数是操作模式,一般使用MODE_PRIVATE
SharedPreferences sharedPreferences = getSharedPreferences("share", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", name);
editor.putString("hobby", hobby);
//提交
editor.commit();

下面是使用SharedPreferences读取信息的核心代码及注释。

SharedPreferences sharedPreferences = getSharedPreferences("share", Context.MODE_PRIVATE);
//第二个参数表示默认值(没有这个属性的话就返回默认值)
String name = sharedPreferences.getString("name","");
String hobby = sharedPreferences.getString("hobby", "");
tv_show_data.setText(String.format("读取到的数据如下:\n姓名:%s\n爱好:%s", name, hobby));

2.例子

下面是一个列子的完整代码。创建SharedPreferencesActivity,代码如下。

  1. activity_shared_preferences.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"
    tools:context=".SharedPreferencesActivity"
    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:text="姓名:"
            android:textSize="18sp"
            android:gravity="center_vertical"
            android:textColor="#000000"/>

        <EditText
            android:layout_toRightOf="@id/tv_name"
            android:inputType="text"
            android:maxLength="11"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_name"
            android:hint="姓名"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <TextView
            android:id="@+id/tv_hobby"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="爱好:"
            android:textSize="18sp"
            android:gravity="center_vertical"
            android:textColor="#000000"/>

        <EditText
            android:id="@+id/et_hobby"
            android:inputType="text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="爱好"
            android:layout_toRightOf="@id/tv_hobby"/>
    </RelativeLayout>

    <Button
        android:id="@+id/btn_ok"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="写入共享参数"/>

    <Button
        android:layout_marginTop="50dp"
        android:text="读取共享参数"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_read"
        />
    <TextView
        android:text="用于展示读取到的参数"
        android:id="@+id/tv_show_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textColor="#000000"/>
</LinearLayout>
  1. SharedPreferencesActivity.java
package xyz.strasae.androidlearn.my;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SharedPreferencesActivity extends AppCompatActivity {
    private EditText et_name;
    private EditText et_hobby;
    private TextView tv_show_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences);
        et_name = findViewById(R.id.et_name);
        et_hobby = findViewById(R.id.et_hobby);
        tv_show_data = findViewById(R.id.tv_show_data);
        findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = et_name.getText().toString();
                String hobby = et_hobby.getText().toString();
                //第一个参数是文件名 第二个参数是操作模式,一般使用MODE_PRIVATE
                SharedPreferences sharedPreferences = getSharedPreferences("share", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("name", name);
                editor.putString("hobby", hobby);
                editor.commit();
                Toast.makeText(SharedPreferencesActivity.this, "写入共享参数成功", Toast.LENGTH_SHORT).show();
            }
        });
        findViewById(R.id.btn_read).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sharedPreferences = getSharedPreferences("share", Context.MODE_PRIVATE);
                //第二个参数表示默认值(没有这个属性的话就返回默认值)
                String name = sharedPreferences.getString("name","");
                String hobby = sharedPreferences.getString("hobby", "");
                tv_show_data.setText(String.format("读取到的数据如下:\n姓名:%s\n爱好:%s", name, hobby));
                Toast.makeText(SharedPreferencesActivity.this, "读取共享参数成功", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值