其他分享
首页 > 其他分享> > Android:SharedPreferences 数据存取

Android:SharedPreferences 数据存取

作者:互联网

目录

SharedPreferences

很多软件都有配置文件,存放程序运行的属性值,如默认欢迎语、登录用户名和密码等。配置用信息的量并不大,采用数据库来存放的话,数据库的连接和数据的操作较为耗时,会影响程序的效率。Android提供了SharedPreferences机制来实现轻量级的数据存储,以键值对(key,value)的方式存储信息。

获得 SharedPreferences 对象

获得 SharedPreferences 对象有两种方式,第一种是通过 getSharedPreferences() 方法得到 SharedPreferences 对象。

public abstract SharedPreferences getSharedPreferences (String name, int mode);
参数 说明
name 保存后 xml 文件的名称
mode xml 文档的操作权限模式

SharedPreferences 有 4 种操作模式:

操作模式 说明
Context.MODE_PRIVATE 默认操作模式,代表该文件是私有数据,只能被应用本身访问,写入的内容会覆盖原文件的内容
Context.MODE APPEND 检查文件是否存在,存在就向文件追加内容,否则就创建新文件
Context.MODE_WORLD_READABLE 当前文件可以被其他应用读取
Context.MODE_WORLD_WRITEABLE 当前文件可以被其他应用写入

第二种是通过 PreferenceManager.getSharedPreferences(Context) 方法获取 SharedPreferences 对象,不能指定 xml 文件名,文件名使用默认的 < package name >+"_preferences.xml" 形式。

数据存入和读取

读写 SharedPreferences 数据要用到 SharedPreferences 接口的 Editor 对象。

public abstract SharedPreferences.Editor edit();

数据存入时通过 SharedPreferences.Editor 接口的 putXxx 方法上传 key-value 对。其中 Xxx 表示不同的数据类型,例如字符串类型的 value 需要用 putString() 方法。

public abstract SharedPreferences.Editor putString(String key, String value);

通过 SharedPreferences.Editor 接口的 commit 方法保存 key-value 对,commit 方法在事件结束后进行提交,将数据保存在数据库中。

public abstract boolean commit();

数据读取时通过 SharedPreferences 对象的键 key 获取对应 key 的键值,不同类型的键值有不同的函数如 getBoolean、getInt、getFloat 和 getLong 等。

public abstract String getString (String key, String defValue);

SharedPreferences 样例

程序需求

使用 SharePreferences 编写信息簿记住用户名、城市及性别等信息,当 APP 退出再次启动能够显示用户输入的信息。

代码编写

activity_main

<?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=".MainActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="用户名"
        android:textSize="15dp"/>
    <EditText
        android:id="@+id/ename"
        android:layout_width="150sp"
        android:layout_height="40sp">
    </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/city"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="城 市 "
            android:textSize="15dp"/>

        <EditText
            android:id="@+id/ecity"
            android:layout_width="150sp"
            android:layout_height="40sp">
        </EditText>

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioGroup
            android:id="@+id/radioGroup1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
        <RadioButton
            android:id="@+id/man"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="男" />
        <RadioButton
            android:id="@+id/woman"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="女" />
    </RadioGroup>
    </LinearLayout>
<Button
    android:id="@+id/submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="提交">
</Button>

</LinearLayout>

MainActivity

package com.example.share;

import android.content.Context;
import android.content.SharedPreferences;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private EditText ename;
    private EditText city;
    private RadioGroup rg;
    private RadioButton man;
    private RadioButton woman;
    private RadioButton radioButton;
    private Button button;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String text;

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

        //绑定对应布局控件
        rg = (RadioGroup) findViewById(R.id.radioGroup1);
        ename = (EditText) findViewById(R.id.ename);
        city = (EditText) findViewById(R.id.ecity);
        man = (RadioButton) findViewById(R.id.man);
        woman=(RadioButton)findViewById(R.id.woman);
        button = (Button) findViewById(R.id.submit);
        SharedPreferences sharedPreferences = getSharedPreferences("test", MODE_PRIVATE);

        //如果不为空
        if (sharedPreferences != null) {

            String nname = sharedPreferences.getString("name", "");
            String ecity = sharedPreferences.getString("city", "");
            text = sharedPreferences.getString("sex", "");
            ename.setText(nname);
            city.setText(ecity);
            if (text.toString().equals("男")){
                man.setChecked(true);
            }
            if (text.toString().equals("女")) {
                woman.setChecked(true);
            }
        }

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1 创建 SharePreferences 对象
                radioButton = (RadioButton)findViewById(rg.getCheckedRadioButtonId());
                String name = ename.getText().toString();
                String ecity = city.getText().toString();
                String sex = radioButton.getText().toString();
                SharedPreferences sharedPreferences = getSharedPreferences("test", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();

                //2  创建Editor对象,写入值
                editor.putString("name", name);
                editor.putString("city", ecity);
                editor.putString("sex", sex);

                //3  提交
                editor.commit();
                Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_LONG).show();
            }
        });
    }
}

运行效果

第一次打开 APP 的效果如下:

输入信息后,再次打开 APP 将显示之前输入的信息:

参考资料

《Android 移动应用开发》,杨谊 主编、喻德旷 副主编,人民邮电出版社

标签:String,private,Editor,SharedPreferences,import,Android,存取,android
来源: https://www.cnblogs.com/linfangnan/p/15856104.html