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

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM