Android:这是一份全面 & 详细的SharePreferences学习指南

1,209 阅读5分钟
原文链接: www.jianshu.com
登录 注册写文章 首页下载APP

Android:这是一份全面 & 详细的SharePreferences学习指南

Carson_Ho 关注 赞赏支持

Android:这是一份全面 & 详细的SharePreferences学习指南

字数 560阅读 0

前言

  • Android中常用的数据存储方式有5种:SharePreferences、SQLite数据库、文件存储、ContentProvider& 网络存储
  • 今天,我将献上一份全面 & 详细的SharePreferences学习指南,希望你们会喜欢。

目录

示意图

1. 简介

  • 定义:一种数据存储方式
  • 本质:以键值对的形式存储在xml中
  • 特点:轻量级
  • 应用场景:轻量级存储(如 应用中的配置、参数属性)
  • 默认存储路径:/data/data/<PackageName>/shared_prefs

2. 对比

除了SharedPreferencesAndroid常见的数据存储方式主要包括:

  • SQLite数据库
  • 文件存储
  • ContentProvider
  • 网络存储

具体介绍如下:

示意图

3. 具体使用

对于SharePreferences的使用,主要包括保存数据 & 读取数据。

3.1 保存数据

  • 本质:以键值对的形式存储在xml文件中
  • 文件存放在/data/data/<packagename>/shared_prefs目录下
  • 使用步骤如下:
// 步骤1
SharedPreferences sharedPreferences =getSharedPreferences("mltest", Context.MODE_PRIVATE);
    // 参数1:指定该文件的名称,名称不用带后缀,后缀会由Android自动加上
    // 参数2:指定文件的操作模式,共有4种操作模式,分别是:
    // Context.MODE_PRIVATE = 0:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
    // Context.MODE_APPEND = 32768:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
    // Context.MODE_WORLD_READABLE = 1:表示当前文件可以被其他应用读取
    // Context.MODE_WORLD_WRITEABLE = 2:表示当前文件可以被其他应用写入

// 步骤2:通过Editor获取编辑器对象
Editor editor = sharedPreferences.edit();

// 步骤3:以键值对的方式写入数据
editor.putString("name", "四种模式");
editor.putInt("age", 4);

// 步骤4:提交修改
editor.commit();

3.2 读取数据

// 步骤1
SharedPreferences sharedPreferences = getSharedPreferences("ljq", Context.MODE_PRIVATE);
    // 参数1:指定该文件的名称,名称不用带后缀,后缀会由Android自动加上
    // 参数2:指定文件的操作模式,共有4种操作模式,分别是:
    // Context.MODE_PRIVATE = 0:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
    // Context.MODE_APPEND = 32768:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
    // Context.MODE_WORLD_READABLE = 1:表示当前文件可以被其他应用读取
    // Context.MODE_WORLD_WRITEABLE = 2:表示当前文件可以被其他应用写入

// 步骤2
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);
// getxxx():xxx为获取数据的数据类型
// 参数1:要获取的key
// 参数2:缺省值,即preference中不存在该key时返回默认值

4. 实例说明

本节将采用完整实例来说明SharePreferences的使用 = 保存数据 + 读取数据。

main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="@string/name"
            android:textSize="20px"
            android:id="@+id/nameLable" />
        <EditText android:layout_width="80px"
            android:layout_height="wrap_content" 
            android:layout_toRightOf="@id/nameLable"
            android:layout_alignTop="@id/nameLable"
            android:layout_marginLeft="10px"
            android:id="@+id/name" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:textSize="20px"
            android:text="@string/age"
            android:id="@+id/ageLable" />
        <EditText android:layout_width="80px"
            android:layout_height="wrap_content" 
            android:layout_toRightOf="@id/ageLable"
            android:layout_alignTop="@id/ageLable"
            android:layout_marginLeft="10px"
            android:id="@+id/age" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="@string/button"
            android:id="@+id/button" />
        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="@string/showButton"
            android:layout_toRightOf="@id/button"
            android:layout_alignTop="@id/button"
            android:id="@+id/showButton" />
    </RelativeLayout>
    <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:textSize="20px"
            android:id="@+id/showText" />
</LinearLayout>

Java文件

package com.ljq.activity;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SpActivity extends Activity {
    private EditText nameText;
    private EditText ageText;
    private TextView resultText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        nameText = (EditText)this.findViewById(R.id.name);
        ageText = (EditText)this.findViewById(R.id.age);
        resultText = (TextView)this.findViewById(R.id.showText);
        
        Button button = (Button)this.findViewById(R.id.button);
        Button showButton = (Button)this.findViewById(R.id.showButton);
        button.setOnClickListener(listener);
        showButton.setOnClickListener(listener);
        
        // 回显
        SharedPreferences sharedPreferences=getSharedPreferences("ljq123", 
                Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
        String nameValue = sharedPreferences.getString("name", "");
        int ageValue = sharedPreferences.getInt("age", 1);
        nameText.setText(nameValue);
        ageText.setText(String.valueOf(ageValue));
    }
    
    private View.OnClickListener listener = new View.OnClickListener(){
        public void onClick(View v) {
            Button button = (Button)v;
            //ljq123文件存放在/data/data/<package name>/shared_prefs目录下
            SharedPreferences sharedPreferences=getSharedPreferences("ljq123", 
                    Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
            switch (button.getId()) {
            case R.id.button:
                String name = nameText.getText().toString();
                int age = Integer.parseInt(ageText.getText().toString());
                Editor editor = sharedPreferences.edit(); //获取编辑器
                editor.putString("name", name);
                editor.putInt("age", age);
                editor.commit();//提交修改
                Toast.makeText(SpActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                break;
            case R.id.showButton:
                String nameValue = sharedPreferences.getString("name", "");
                int ageValue = sharedPreferences.getInt("age", 1);
                resultText.setText("姓名:" + nameValue + ",年龄:" + ageValue);
                break;
            }
        }
    };
}

5. 总结

  • 本文全面讲解Android中常用的数据存储方式SharePreferences
  • 接下来,我会继续讲解Androdi中其他常用的数据存储方式,具体包括:SQLite数据库、文件存储、ContentProvider& 网络存储,感兴趣的同学可以继续关注本人的技术博客:carson_ho的技术博客

请点赞!因为你的鼓励是我写作的最大动力!

相关文章阅读
Android开发:最全面、最易懂的Android屏幕适配解决方案
Android事件分发机制详解:史上最全面、最易懂
Android开发:史上最全的Android消息推送解决方案
Android开发:最全面、最易懂的Webview详解
Android开发:JSON简介及最全面解析方法!
Android四大组件:Service服务史上最全面解析
Android四大组件:BroadcastReceiver史上最全面解析


欢迎关注Carson_Ho的简书!

不定期分享关于安卓开发的干货,追求短、平、快,但却不缺深度

上一篇 查看连载目录 下一篇 0人点赞   Carson_Ho 拥有4730钻 (约577.15元) 关注 "关注微信公众号:【carson带你解析Android】,带你高效、系统地学习Android知识" 赞赏   Android常用 47486字 647302阅读 977人关注 关注 广告 Carson_Ho关注 拥有4730钻 (约577.15元) 一文带你全面了解MVC、MVP、MVVM模式(含实例讲解) 阅读 3775 Android:关于 Intent的那些小事(介绍、使用方法等) 阅读 734 Android:图文解析带你快速了解RxJava原理 阅读 2141

精彩继续

3分钟学会如何在饭局上尬聊 阅读 4962 成年人社交中,没人告诉你的3个潜规则 阅读 5004 广告 评论0 赞1赞 赞赏