Android之SharedPreferences数据存储

一、SharedPreferences保存数据介绍

  如果有想要保存的相对较小键值集合,应使用SharedPreferences API。SharedPreferences对象指向包含键值对的文件并提供读写这些文件的简单方法。每个SharedPreferences文件由框架进行管理并且可以专用或共享。

  SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中重载窗口状态onSaveInstancesState保存一般使用SharedPreferences完成,它提供了Android平台常规的Long长整形、Int整形、String字符串型的保存。

  处理方式:SharedPreferences类似过去的Windows系统上的ini配置文件,但它分为多种权限,可以全局共享访问 ,Android提示最终是以xml方式来保存,整体效率来看不是特别高,对于常规的轻量级而言要比SQLite要好不少如果真的存储量不大可以考虑自己定义文件格式。Xml处理时Dalvik会通过自带底层的本地XML Parser解析,比如XML pull方式,这样对于内存资源占用比较好。它的本质是基于xml文件存储key-value键值对数据,通过用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改通过Editor对象实现。

  SharedPreferences对象与SQLite数据库相比,免去了创建数据库、创建表、写SQL语句等诸多操作,相对而言更加方便、简洁。但是SharedPreferences也有其自身缺陷,比如其职能存储boolean、int、float、long和string五种简单的数据类型,比如其无法进行条件查询等。所依不论SharedPreferences的数据存储操作是如何简单,它也只能是存储方式的一种补充,而无法完全替代如SQLite数据库这样的数据存储方式。

  SharedPreferences API仅用于读写键值对,不得将其与Preferences API混淆,后者帮助为应用设置构建用户界面。

二、使用方法

1.根据Context获取SharedPreferences对象

private Context mContext;
private SharedPreferences mSharedPreferences;
...
mSharedPreferences =mContext.getSharedPreferences
                (PREFRENCE_FILE_KEY, Context.MODE_PRIVATE);

第一个参数是文件名;第二个参数是文件的操作权限。

操作权限有:

Context.MODE_PRIVATE :为默人操作模式,代表改文件时私有数据,只能被应用本身访问,在改模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中,可以使用Context.MODE_APPEND。
Context.MODE_APPEND :模式会检查文件是否存在,存在就往文件追加,否则就创建新文件。
Context.MODE_WORLD_READABLE与Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写文件。
Context.MODE_WORLD_READABLE :表示当前文件可以被其他应用读取。
Context.MODE_WORLD_WRITEABLE :表示当前文件可以被其他应用写入。
 

获取SharedPreferences对象有两种方式:

(1)调用Context对象的getSharedPreferences()方法;

(2)调用Activity对象的getPreferences()对象。

两种方式的区别:调用Context对象的getSharedPreferences()方法获得的SharedPreferences对象可以被同一应用程序下的其他组件共享。调用Activity对象的getPrefrences()方法获得的SharedPreferences对象只能在该Activity中使用。

2.利用edit()方法获取Editor对象

SharedPreferences.Editor editor = mSharedPreferences.edit();

3.通过Editor对象存储key-value键值对数据

editor.putInt("id",person._id);
editor.putString("name",person.name);

4.通过commit()方法提交数据

editor.commit();

5.通过SharedPreferences对象读取数据

 int id = mSharedPreferences.getInt("id",0);
String name = mSharedPreferences.getString("name", "defaultname");

第二个参数是数值的默认值。

三、小案例

1.添加strings.xml文件

<string name="write_data">写入数据</string>
<string name="read_data">读取数据</string>
<string name="preference_file_key">com.zhangmiao.datastoragedemo.PREFRENCE_FILE_KEY</string>

2.修改activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.zhangmiao.datastoragedemo.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="@string/content_provider" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/fab_margin"
            android:layout_marginTop="@dimen/fab_margin"
            android:orientation="horizontal">

            <Button
                android:id="@+id/provider_add"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/add_data" />

            <Button
                android:id="@+id/provider_delete"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/delete_data" />

            <Button
                android:id="@+id/provider_update"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/update_data" />

            <Button
                android:id="@+id/provider_query"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/query_data" />

        </LinearLayout>

        <TextView
            android:id="@+id/table_info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/app_name" />
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

3.添加Person类

package com.zhangmiao.datastoragedemo;

/**
 * Created by zhangmiao on 2016/12/16.
 */
public class Person {

    public int _id;
    public String name;
    public int age;
    public String info;

    public Person() {

    }

    public Person(int _id,String name, int age, String info){
        this._id = _id;
        this.name = name;
        this.age = age;
        this.info = info;
    }
}

4.添加SharedPreferencesDBManager类

package com.zhangmiao.datastoragedemo;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by zhangmiao on 2016/12/19.
 */
public class SharedPreferencesDBManager {

    private Context mContext;
    private SharedPreferences mSharedPreferences;
    private final static String PREFRENCE_FILE_KEY = "com.zhangmiao.datastoragedemo.PREFRENCE_FILE_KEY";

    public SharedPreferencesDBManager(Context context){
        mContext = context;
        mSharedPreferences =mContext.getSharedPreferences
                (PREFRENCE_FILE_KEY, Context.MODE_PRIVATE);
    }

    public void writeData(Person person)
    {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putInt("id",person._id);
        editor.putString("name",person.name);
        editor.putInt("age",person.age);
        editor.putString("info",person.info);
        editor.commit();
    }

    public Person readData(){
        int id = mSharedPreferences.getInt("id",0);
        String name = mSharedPreferences.getString("name", "defaultname");
        int age = mSharedPreferences.getInt("age", 0);
        String info = mSharedPreferences.getString("info", "defaultinfo");
        Person person = new Person(id,name,age,info);
        return person;
    }
}

5.修改MainActivity类

package com.zhangmiao.datastoragedemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {private SharedPreferencesDBManager mSPManager;

    private TextView mTableInfo;

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

        mSPManager = new SharedPreferencesDBManager(this);

        Button spWrite = (Button) findViewById(R.id.shared_read);
        Button spRead = (Button) findViewById(R.id.shared_write);

        mTableInfo = (TextView) findViewById(R.id.table_info);

        spWrite.setOnClickListener(this);
        spRead.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {case R.id.shared_read:
                writeTableInfo(mSPManager.readData());
                break;
            case R.id.shared_write:
                Person person2 = new Person(1,"zhang", 18, "women");
                mSPManager.writeData(person2);
                break;
            default:
                break;
        }
    }

    private void writeTableInfo(Person person) {
        String message = "";
        message += "id: " + person._id + " name: " + person.name
                + " age: " + person.age + " info: " + person.info + "
";
        mTableInfo.setText(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

代码下载地址:https://github.com/ZhangMiao147/DataStorageDemo

原文地址:https://www.cnblogs.com/zhangmiao14/p/6201900.html