Carson带你学Android:数据存储SharePreferences学习指南

前言

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

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


目录

示意图

1. 简介

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

2. 对比

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

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

具体介绍如下:

示意图


3. 具体使用

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

3.1 保存数据

  • 本质:以键值对的形式存储在xml文件中
  • 文件存放在/data/data//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. 总结


欢迎关注Carson_Ho的CSDN博客 与 公众号!

博客链接:https://carsonho.blog.csdn.net/


请帮顶 / 评论点赞!因为你的鼓励是我写作的最大动力!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值