Android_存储之SharedPreferences

一、概述

SharedPreferences是一种轻量级的数据存储方式,采用键值对的存储方式。

SharedPreferences只能存储少量数据,大量数据不能使用该方式存储,支持存储的数据类型有booleans, floats, ints, longs, and strings。

SharedPreferences存储到一个XML文件中的,路径在/data/data/<packagename>/shared_prefs/下,文件名以及存储后面详细讲述。

 

二、基本用法

1.获取SharedPreferences对象

要创建存储文件或访问已有数据,首先要获取SharedPreferences才能进行操作。获取SharedPreferences对象有下面两个方式:

(1)getSharedPreferences(String name, int mode) --- 通过Context调用该方法获得对象。它有两个参数,第一个name 指定了SharedPreferences存储的文件的文件名,第二个参数mode 指定了操作的模式。这种方式获取的对象创建的文件 可以被整个应用所有组件使用,有指定的文件名。

(2)getPreferences(int mode) --- 通过Activity调用获得对象。它只有一个参数mode 指定操作模式。这种方式获取的对象创建的文件 属于Activity,只能在该Activity中使用,且没有指定的文件名,文件名同Activity名字。

如:

mContextSp = this.getSharedPreferences( "testContextSp", Context.MODE_PRIVATE );
---创建的文件名是,testContextSp.xml mActivitySp
= this.getPreferences( Context.MODE_PRIVATE );
---创建的文件名是,MainActivity.xml(该Activity叫MainActivity)

 

操作模式(mode):

两个方式都有一个mode参数,mode具体有4个值,最新的只能使用默认模式 Context.MODE_PRIVATE。

Context.MODE_PRIVATE(0):默认模式,创建的文件只能由 调用的应用程序(或者共享相同用户ID的应用程序)访问

 

后面3种已不推荐使用。从下面文档说明中看到,这些情况的操作 最好使用ContentProvider, BroadcastReceiver, Service.

这些在前面四大组件中详细写过,最后面附上链接:

ContentProvider:https://www.cnblogs.com/fanglongxiang/p/11304243.html

BroadcastReceiver:https://www.cnblogs.com/fanglongxiang/p/11281466.html

Service:https://www.cnblogs.com/fanglongxiang/p/11113942.html

Context.MODE_WORLD_READABLE(1) 

Context.MODE_WORLD_WRITEABLE(2) 

Context.MODE_MULTI_PROCESS(4)

 

2.数据更新

SharedPreferences添加或更新数据,通过SharedPreferences 获取 SharedPreferences.Editor,操作文件数据,最后通过commit()或apply()提交修改。

如下:

SharedPreferences mContextSp = this.getSharedPreferences( "testContextSp", Context.MODE_PRIVATE );
SharedPreferences.Editor editor = mContextSp.edit();
editor.putInt( "age", 28);
editor.putBoolean( "isStudent", false );
editor.putString( "job", "it" );
editor.commit();

操作后,在对应应用路径下有创建testContextSp.xml。具体手机里的数据如下。

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="job">it</string>
    <int name="age" value="28" />
    <boolean name="isStudent" value="false" />
</map>

 

commit()和apply()区别:

 apply()立即更改内存中的SharedPreferences对象,但异步地将更新写入磁盘。commit()同步地将数据写入磁盘。commit()是同步的,在主线程调用它应该多注意,因为可能引起阻塞,引起ANR。

commit()有返回值,返回是否成功写入永久性存储种。apply()没有返回值。

 

(3)数据获取。

通过SharedPreferences提供的getInt(),getString()等方法获取 文件中的数据,如果数据不存在,则返回一个默认值。

如:

mContextSp = this.getSharedPreferences( "testContextSp", Context.MODE_PRIVATE );
String name = mContextSp.getString( "name", "bbb" );
int age = mContextSp.getInt( "age", 0 );
boolean isStudent = mContextSp.getBoolean( "isStudent", false );

 

三、简单实例

一个Activity里3个按钮,AddData   UpdateData  getData,具体代码如下,让我们看看操作后手机中的数据变化。

MainActivity.java

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    SharedPreferences mContextSp;
    SharedPreferences mActivitySp;

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

        mContextSp = this.getSharedPreferences( "testContextSp", Context.MODE_PRIVATE );
        mActivitySp = this.getPreferences( Context.MODE_PRIVATE );
        mActivitySp.edit().commit();//only create file


        Button addBtn = findViewById( R.id.add_data_btn );
        addBtn.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = mContextSp.edit();
                editor.putString( "name", "aaa" );
                editor.putInt( "age", 18);
                editor.putBoolean( "isStudent", true );
                editor.commit();
            }
        } );

        Button updateBtn = findViewById( R.id.update_data_btn );
        updateBtn.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = mContextSp.edit();
                editor.putInt( "age", 28);
                editor.putBoolean( "isStudent", false );
                editor.putString( "job", "it" );
                editor.commit();
            }
        } );

        Button getDataBtn = findViewById( R.id.get_data_btn );
        getDataBtn.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = mContextSp.getString( "name", "bbb" );
                int age = mContextSp.getInt( "age", 0 );
                boolean isStudent = mContextSp.getBoolean( "isStudent", false );
                Log.d( "sp_test", "name="+name+";age="+age+";isStudent="+isStudent);
            }
        } );
    }
}

布局文件activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button android:id="@+id/add_data_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="AddData"/>

    <Button android:id="@+id/update_data_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="UpdateData"/>

    <Button android:id="@+id/get_data_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="getData"/>

</LinearLayout>

具体操作及现象:

启动应用,mActivitySp.edit().commit(); 通过getPreferences()获取的SharedPreferences对象 创建了一个不指定名称的xml文件,文件名同Activity名字,没写入任何数据。

点击AddData 添加数据, 然后点击getData 获取数据。

getData打印出的log:

2019-08-22 10:49:41.626 21272-21272/com.flx.testsharedpreferences D/sp_test: name=aaa;age=18;isStudent=true

 获取的数据和手机中数据是一致的。 

 

点击UpdateData 更新数据,在点击getData 获取数据。

getData打印的数据:

2019-08-22 10:53:01.580 21272-21272/com.flx.testsharedpreferences D/sp_test: name=aaa;age=28;isStudent=false

  

 

posted @ 2019-09-08 22:06  流浪_归家  阅读(33272)  评论(5编辑  收藏  举报