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

前言

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

相关系列文章阅读
Carson带你学Android:学习方法
Carson带你学Android:四大组件
Carson带你学Android:自定义View
Carson带你学Android:异步-多线程
Carson带你学Android:性能优化
Carson带你学Android:动画


欢迎关注Carson_Ho的简书

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


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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,829评论 1 331
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,603评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,846评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,600评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,780评论 3 272
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,695评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,136评论 2 293
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,862评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,453评论 0 229
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,942评论 2 233
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,347评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,790评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,293评论 3 221
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,839评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,448评论 0 181
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,564评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,623评论 2 249

推荐阅读更多精彩内容