2025-05-23

 

在開發應用程序的過程中,有時候我們需要記錄用戶的偏好,或者用戶名密碼之類。這就要涉及到數據的存儲,android平臺下存儲數據的方式主要有如下幾種方式:

 

Shared Preferences

Store private primitive data in key-value pairs.  輕量的以鍵值對的形式進行存儲

Internal Storage

Store private data on the device memory. 設備上的文件存儲

External Storage

Store public data on the shared external storage. 外部的文件存儲,一般指存儲在SD卡上的文件,優勢是不隨程序卸載而刪除

SQLite Databases

Store structured data in a private database. 這個比較常見瞭數據庫

Network Connection

Store data on the web with your own network server.  網絡獲取

     那麼今天主要和大傢分享的是第一種Shareepreference ,這是android提供的一個輕量級的數據存儲框架,形式就是鍵值對的形式,熟悉xml的朋友應該比較習慣這種風格,就是“屬性名-屬性值”的形式。從名字就可以看出,這個框架主要是用於設置用戶的一個偏好,他的一個特點是可以跨session的共享,在多個activity之間可以操作,如果設置特別的權限,其他應用也可以訪問。下面就是使用的一個基本方法。

    1:獲取類型SharedPreferences

     主要有兩種方式可以獲得

     

getSharedPreferences() 接受兩個參數,第一個是文件標示,第二個是權限,用於創建多個配置文件的場景

getPreferences() – 隻有文件權限參數,與上一個不同在於隻創建一個文件。

   今天詳細介紹一下第一個方法~

   首先看來自官方API的介紹

public abstract SharedPreferences getSharedPreferences (String name, int mode)

 

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

解釋:該方法用於從上下文,(可以理解為我們的Context文件,相信寫過各種服務的朋友並不陌生)取回並維護一個名為name的配置文件。返回一個SharedPreferences對象,我們可以通過這個對象編輯和獲取鍵值。每一個時刻隻有一個SharedPreferencesd實例會被調用。效果是,每一個調用者可以立刻看到其他調用者編輯的效果。

Parameters

 

name       Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).

解釋:需要的文件名字,如果不存在的話,當你調用editor的時候(用於編輯偏好文件,下面會介紹)會自動創建。

mode      Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions. The bit MODE_MULTI_PROCESS can also be used if multiple processes are mutating the same SharedPreferences file.MODE_MULTI_PROCESS is always on in apps targetting Gingerbread (Android 2.3) and below, and off by default in later versions.

 

解釋:操作模式 一共有四種,下面逐一解釋

Returns

 

Returns the single SharedPreferences instance that can be used to retrieve and modify the preference values.

See Also

 

MODE_PRIVATE         這是默認的形式,配置文件隻允許本程序和享有本程序ID的程序的訪問

MODE_WORLD_READABLE   允許其他的應用程序讀文件

MODE_WORLD_WRITEABLE   允許其他的應用程序寫文件

MODE_MULTI_PROCESS       主要用於多任務,2.3版本當多個進程共同訪問的時候,必須指定這個標簽

 

有瞭SharedPreferences對象我們還需要一個Editor來進行偏好的編輯與設置。

    Editor主要包含一些putXXX方法,支持booleans, floats, ints, longs, and strings.幾種類型,最後完成添加後,一定要調用commit方法或者apply方法進行修改後的提交。

    如果想得到value的話就自己直接用SharedPreference類來使用相應的getxxx方法就好瞭。

    不多說瞭,奉上一段自己臨時寫的一段非常簡單的代碼,與大傢分享

    

 

 

view plain

package com.yui; 

 

import android.content.Context; 

import android.content.SharedPreferences; 

import android.content.SharedPreferences.Editor; 

import android.os.Bundle; 

import android.preference.PreferenceActivity; 

import android.util.Log; 

/**

 * 演示android SharedPreference的一個demo

 * @author Octobershiner

 * @version 1.0 2011/11/4

 * */ 

public class PreferActivity extends PreferenceActivity { 

    /** Called when the activity is first created. */ 

     

    //設置一些標簽 

    private static final String MY_SETTING = "mySetting"; 

    private static final String COLOR = "color"; 

    private static final String DEFAULT_COLOR = "blue"; 

     

    @Override 

    public void onCreate(Bundle savedInstanceState) { 

        super.onCreate(savedInstanceState); 

        setContentView(R.layout.main); 

         

        //get the setting files  

        SharedPreferences myPreference = this.getSharedPreferences(MY_SETTING, Context.MODE_PRIVATE); 

        //edit the file 

        Editor editor = myPreference.edit(); 

        editor.putString(COLOR, "red"); 

         

        /**

         * 解釋一下這個函數,當myPreference發現沒有COLOR屬性存在的時候

         * 會將DEFAULT_COLOR的賦給temp

         * 大傢可以試一下把前面的putString註釋掉,log的記過就不同瞭

         * */ 

        String temp = myPreference.getString(COLOR, DEFAULT_COLOR); 

        //利用Log顯示一些結果       

        Log.i("TAG","now i prefer "+temp); 

    } 

 

在最後,我想問一個問題,小O是看瞭android 2.3的SDK源代碼,但是發現,SharedPreference隻是一個接口,我並沒有找到它的實現,網上也沒有相應的解答,希望瞭解的朋友能及時的聯系我,交流一下,謝謝,十一點瞭,實驗室沒人瞭,準備回去睡覺~~、

 

摘自 Octobershiner的專欄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *