【Android應用開發技術:資料存放區】SharedPreferences

來源:互聯網
上載者:User

標籤:

郭孝星
微博:郭孝星的新浪微博
郵箱:[email protected]
部落格:http://blog.csdn.net/allenwells
Github:https://github.com/AllenWells

應用程式一般都會涉及資料的輸入和輸出,應用程式的參數設定、程式運行狀態資料等等這些都需要儲存的外部儲存空間上,如果有大量資料需要儲存則需要藉助資料庫,如果只有少量的資料需要儲存,而且這些資料格式簡單,則可以使用Sharedreferences來進行儲存。

SharedPreferences儲存的資料主要是類似於配置資訊格式的資料,因此它儲存的資料主要是簡單類型的key-value對。

在進行資料的讀取和寫入之前,我們首先要建立SharedPreferences,它本身是個介面,無法直接建立執行個體,建立方法如下所示:

Context context = getActivity();SharedPreferences sharedPref = context.getSharedPreferences(        getString(com.alenwells.app.settings), Context.MODE_PRIVATE);
  • 建立名稱:當命名我們的SharedPreferences時,我們應該採用類似於com.alenwells.app.settings這樣的方式來命名。
  • 建立類型
    • Context.tMODE_PRIVATe:SharedPreferences只能被本應用讀寫,
    • Context.MODE_WORLD_READABLE:SharedPreferences可以被其它應用讀,但不能寫。
    • Context.MODE_WORLD_WRITEABLE :SharedPreferences可以被其他應用讀寫。

SharedPreferences建立成功後會儲存在/data/data//shared_prefs/目錄下,它是一個XML檔案,以為根項目,以

一 資料的讀取

SharedPreferences即可主要負責讀取應用程式的配置資料,它提供以下方法來訪問SharedPreferences中的key-value對。

(1) boolean contains(String key)

判斷SharedPreferences是否包含特定的key的資料。

/** * Checks whether the preferences contains a preference. *  * @param key The name of the preference to check. * @return Returns true if the preference exists in the preferences, *         otherwise false. */boolean contains(String key);
(2) Map
/** * Retrieve all values from the preferences. * * <p>Note that you <em>must not</em> modify the collection returned * by this method, or alter any of its contents.  The consistency of your * stored data is not guaranteed if you do. * * @return Returns a map containing a list of pairs key/value representing * the preferences. * * @throws NullPointerException */Map<String, ?> getAll();
(3) boolean getXxx(String key, xxx defValue)

擷取SharedPreferences資料裡指定key對應的value,如果key不存在則返回預設值,其中xxx可以是
boolean、float、int、long和String等基本類型的值。

舉例

讀取其他應用SharedPreferences

import org.crazyit.other.R;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.content.pm.PackageManager.NameNotFoundException;import android.os.Bundle;import android.widget.TextView;public class ReadOtherPreferences extends Activity{    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        Context useCount = null;        try        {            // 擷取其他程式所對應的Context            useCount = createPackageContext("org.crazyit.io",                Context.CONTEXT_IGNORE_SECURITY);        }        catch (NameNotFoundException e)        {            e.printStackTrace();        }        // 使用其他程式的Context擷取對應的SharedPreferences        SharedPreferences prefs = useCount.getSharedPreferences("count",            Context.MODE_WORLD_READABLE);        // 讀取資料        int count = prefs.getInt("count", 0);        TextView show = (TextView) findViewById(R.id.show);        // 顯示讀取的資料內容        show.setText("UseCount應用程式以前被使用了" + count + "次。");    }}
二 資料寫入

SharedPreferences只用來讀取資料,它本身並沒有寫入資料的能力,寫入資料通過內部介面Editor來完成。

擷取Editor對象

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPref.edit();

SharedPreferences.Editor提供一下方法來寫入資料。

(1) Editor clear()

清空SharedPreferences裡所有資料。

/*** Mark in the editor to remove <em>all</em> values from the* preferences.  Once commit is called, the only remaining preferences* will be any that you have defined in this editor.** <p>Note that when committing back to the preferences, the clear* is done first, regardless of whether you called clear before* or after put methods on this editor.** @return Returns a reference to the same Editor object, so you can* chain put calls together.*/Editor clear();
(2) Editor putXxx(String key, xxx value)

向SharedPreferences存入指定key對應的資料,其中xxx可以是boolean、float、int、long和String等基本類型的值。

(3) Editor remove(String key)

刪除SharedPreferences裡指定key的資料項目。

/** * Mark in the editor that a preference value should be removed, which * will be done in the actual preferences once {@link #commit} is * called. *  * <p>Note that when committing back to the preferences, all removals * are done first, regardless of whether you called remove before * or after put methods on this editor. *  * @param key The name of the preference to remove. *  * @return Returns a reference to the same Editor object, so you can * chain put calls together. */Editor remove(String key);
(4) boolean commit()

提交修改

/** * Commit your preferences changes back from this Editor to the * {@link SharedPreferences} object it is editing.  This atomically * performs the requested modifications, replacing whatever is currently * in the SharedPreferences. * * <p>Note that when two editors are modifying preferences at the same * time, the last one to call commit wins. * * <p>If you don‘t care about the return value and you‘re * using this from your application‘s main thread, consider * using {@link #apply} instead. * * @return Returns true if the new values were successfully written * to persistent storage. */boolean commit();

從用法角度來看,SharedPreferences和SharedPreferences.Editor的組合非常類似於Map。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【Android應用開發技術:資料存放區】SharedPreferences

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.