android之SharedPreferences進行資料存放區

來源:互聯網
上載者:User

首先我們來介紹一下SharedPreferences這個介面的作用:

       我們都知道,很多時候我們對於系統依賴的一些參數設定總是會放到一個設定檔中,例如在java中我們通常會用到*.properties檔案;在android中,我們也有類似於*.properties的一類檔案,而這類檔案在android中的對象表現形式,就是SharedPreferences。你可以認為,每個應用中使用的SharedPreferences是該應用檔案的一個映射。

      現在,我們知道了,sharedPreferences介面可以讓我們儲存一些值。

在SharedPreferences的api說明中,我們可以看到這樣一段介紹。

Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. </p><p>Note: currently this class does not support use across multiple processes. This will be added later.</p><p>

翻譯如下:

       SharedPreferences介面一般用來訪問或修改由方法getSharedPreferences(String,int)返回的設定資訊。這裡的設定資訊都是單例唯一的,這就意味著改設定資訊會被所以安裝了該APK應用的用戶端(手機)所共用。如果我們要想修改這些設定資訊,我們則必須要通過SharedPreferences.Editor對象進行修改,至於為什麼一定要擷取這個Editor對象之後才可以修改呢,原因是這樣的,我們前面已經說了,改配置資訊會被所有的用戶端共用,那就意味著同一時刻可能有好幾個用戶端要對配置資訊中的值進行修改,這很容易出現資料修改混亂的問題,這裡通過擷取SharedPreferences.Editor對象就是為了保證資料的一致性。注意,到目前為止,SharedPreferences是不支援多進程的,該功能處於待添加狀態。

      我們再來看看,該介面中主要的方法有哪些:

 

           

     SharedPreferences包含兩個內部類,SharedPreferences.Editor和SharedPreferences.OnSharedPreferencesChangeListener;其中Editor主要在對屬性設定進行修改時使用,而OnSharedPreferencesChangeListener則是在屬性被修改時觸發的一個事件,我們可以在裡面做一些額外的動作,如根據新的屬性值去觸發一些頁面的改變了,等等……

 

     

     至於其他的方法,都很簡單,一看方法名就知道啥意思了,我就不詳細介紹了。現在給大家貼一個應用的例子:

 

先:

然後是main.xml

<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:orientation="vertical"<br /> android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"<br /> ><br /><TextView<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:id="@+id/textView"<br /> /><br /></LinearLayout><br />

activity的代碼:

package cn.com.sharedPreferencesTest;</p><p>import android.app.Activity;<br />import android.content.SharedPreferences;<br />import android.os.Bundle;<br />import android.util.Log;<br />import android.widget.TextView;</p><p>public class SharedPreferencesActivity extends Activity {<br /> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main);<br /> saveSharedPreferences();<br /> readSharedPreferences();</p><p> }</p><p> /**<br /> * @author chenzheng_java<br /> * @description 建立並儲存一些設定資訊<br /> * @since 2011/03/05<br /> */<br /> private void saveSharedPreferences(){<br /> /*<br /> * getSharedPreferences(String name,int mode)方法是在Context中定義的抽象方法,在ContextWrapper中進行了具體實現,<br /> * 該方法會根據使用者傳遞的名稱和寫入類型建立一個SharedPreferences對象進行返回。<br /> * 在Activity中,還有一個方法可以回去SharedPreferences對象,這個方法就是SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);<br /> * 改方法在Activity中定義並實現,這裡沒有name參數是因為該方法預設將當前Activity的類名作為name屬性(這裡的類名並不包含包路徑哦)<br /> * */<br /> SharedPreferences sharedPreferences = getSharedPreferences("preferences", MODE_PRIVATE);</p><p> //儲存資料<br /> SharedPreferences.Editor editor = sharedPreferences.edit();<br /> editor.putString("name", "蔡依林");<br /> editor.putInt("age", 31);<br /> Boolean b = editor.commit();</p><p> if(b){<br /> Log.i("通知:", "儲存成功!");<br /> }else{<br /> Log.i("通知", "儲存失敗!");<br /> }</p><p> }</p><p> /**<br /> * @author chenzheng_java<br /> * @description 讀取我們添加到SharedPreference對象中的資料<br /> * @since 2011/03/05<br /> */<br /> private void readSharedPreferences(){<br /> String result = "美女資訊:/n" ;<br /> SharedPreferences sharedPreferences = this.getSharedPreferences("preferences", MODE_PRIVATE);<br /> result+=" 姓名 "+sharedPreferences.getString("name", "暫時沒有人");<br /> result+=" 年齡"+sharedPreferences.getInt("age", -1);<br /> TextView textView = (TextView)findViewById(R.id.textView);<br /> textView.setText(result);</p><p> }</p><p>}

其他的都為預設。

---------------------------------------------------------------------

最後了,說點廢話

SharedPreferences實際上是按照索引值對的方式進行資料存放區的,如果同一個key被設定了兩次值,那麼後來的值將會覆蓋掉前面的值。實際上,SharedPreferences在後台是使用XML檔案的格式進行儲存資料的,其儲存的目錄為/data/data/應用程式套件名稱/shared_prefs。

如:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?><br /><map><br /><int name="age" value="31" /><br /><string name="name">蔡依林</string><br /></map><br />

而且SharedPreferences對象對於儲存值的格式是有嚴格要求的,從方法中我們可以看到,只能儲存String/int/long/Float/Boolean幾種類型的資料。

------------------------------------------------------------------------------------

小技巧:如果我們在當前的activity中想訪問另一個activity(如cn.com.abc.activityTest)的SharedPreferences對象,我們應該如何擷取呢?

  應該如下擷取

 

// 擷取包含cn.com.abc.activityTest的那個context對象,然後通過context對象來擷取,注意這裡的mode必須為Context.MODE_WORLD_READABLE</p><p>Context otherAppContext = createPackageContext("cn.com.abc.activityTest", Context.CONTEXT_IGNORE_SECURITY);</p><p>SharedPreferences sharedPreferences = otherAppContext.getSharedPreferences("preferences", Context.MODE_WORLD_READABLE);</p><p> 

--------------------------------------------------------------

最後粘貼上SharedPreferences的源碼,方便查閱。

 /*<br /> * Copyright (C) 2006 The Android Open Source Project<br /> *<br /> * Licensed under the Apache License, Version 2.0 (the "License");<br /> * you may not use this file except in compliance with the License.<br /> * You may obtain a copy of the License at<br /> *<br /> * http://www.apache.org/licenses/LICENSE-2.0<br /> *<br /> * Unless required by applicable law or agreed to in writing, software<br /> * distributed under the License is distributed on an "AS IS" BASIS,<br /> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br /> * See the License for the specific language governing permissions and<br /> * limitations under the License.<br /> */</p><p>package android.content;</p><p>import java.util.Map;</p><p>/**<br /> * Interface for accessing and modifying preference data returned by {@link<br /> * Context#getSharedPreferences}. For any particular set of preferences,<br /> * there is a single instance of this class that all clients share.<br /> * Modifications to the preferences must go through an {@link Editor} object<br /> * to ensure the preference values remain in a consistent state and control<br /> * when they are committed to storage.<br /> *<br /> * <p><em>Note: currently this class does not support use across multiple<br /> * processes. This will be added later.</em><br /> *<br /> * @see Context#getSharedPreferences<br /> */<br />public interface SharedPreferences {<br /> /**<br /> * Interface definition for a callback to be invoked when a shared<br /> * preference is changed.<br /> */<br /> public interface OnSharedPreferenceChangeListener {<br /> /**<br /> * Called when a shared preference is changed, added, or removed. This<br /> * may be called even if a preference is set to its existing value.<br /> *<br /> * @param sharedPreferences The {@link SharedPreferences} that received<br /> * the change.<br /> * @param key The key of the preference that was changed, added, or<br /> * removed.<br /> */<br /> void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key);<br /> }</p><p> /**<br /> * Interface used for modifying values in a {@link SharedPreferences}<br /> * object. All changes you make in an editor are batched, and not copied<br /> * back to the original {@link SharedPreferences} or persistent storage<br /> * until you call {@link #commit}.<br /> */<br /> public interface Editor {<br /> /**<br /> * Set a String value in the preferences editor, to be written back once<br /> * {@link #commit} is called.<br /> *<br /> * @param key The name of the preference to modify.<br /> * @param value The new value for the preference.<br /> *<br /> * @return Returns a reference to the same Editor object, so you can<br /> * chain put calls together.<br /> */<br /> Editor putString(String key, String value);</p><p> /**<br /> * Set an int value in the preferences editor, to be written back once<br /> * {@link #commit} is called.<br /> *<br /> * @param key The name of the preference to modify.<br /> * @param value The new value for the preference.<br /> *<br /> * @return Returns a reference to the same Editor object, so you can<br /> * chain put calls together.<br /> */<br /> Editor putInt(String key, int value);</p><p> /**<br /> * Set a long value in the preferences editor, to be written back once<br /> * {@link #commit} is called.<br /> *<br /> * @param key The name of the preference to modify.<br /> * @param value The new value for the preference.<br /> *<br /> * @return Returns a reference to the same Editor object, so you can<br /> * chain put calls together.<br /> */<br /> Editor putLong(String key, long value);</p><p> /**<br /> * Set a float value in the preferences editor, to be written back once<br /> * {@link #commit} is called.<br /> *<br /> * @param key The name of the preference to modify.<br /> * @param value The new value for the preference.<br /> *<br /> * @return Returns a reference to the same Editor object, so you can<br /> * chain put calls together.<br /> */<br /> Editor putFloat(String key, float value);</p><p> /**<br /> * Set a boolean value in the preferences editor, to be written back<br /> * once {@link #commit} is called.<br /> *<br /> * @param key The name of the preference to modify.<br /> * @param value The new value for the preference.<br /> *<br /> * @return Returns a reference to the same Editor object, so you can<br /> * chain put calls together.<br /> */<br /> Editor putBoolean(String key, boolean value);</p><p> /**<br /> * Mark in the editor that a preference value should be removed, which<br /> * will be done in the actual preferences once {@link #commit} is<br /> * called.<br /> *<br /> * <p>Note that when committing back to the preferences, all removals<br /> * are done first, regardless of whether you called remove before<br /> * or after put methods on this editor.<br /> *<br /> * @param key The name of the preference to remove.<br /> *<br /> * @return Returns a reference to the same Editor object, so you can<br /> * chain put calls together.<br /> */<br /> Editor remove(String key);</p><p> /**<br /> * Mark in the editor to remove <em>all</em> values from the<br /> * preferences. Once commit is called, the only remaining preferences<br /> * will be any that you have defined in this editor.<br /> *<br /> * <p>Note that when committing back to the preferences, the clear<br /> * is done first, regardless of whether you called clear before<br /> * or after put methods on this editor.<br /> *<br /> * @return Returns a reference to the same Editor object, so you can<br /> * chain put calls together.<br /> */<br /> Editor clear();</p><p> /**<br /> * Commit your preferences changes back from this Editor to the<br /> * {@link SharedPreferences} object it is editing. This atomically<br /> * performs the requested modifications, replacing whatever is currently<br /> * in the SharedPreferences.<br /> *<br /> * <p>Note that when two editors are modifying preferences at the same<br /> * time, the last one to call commit wins.<br /> *<br /> * @return Returns true if the new values were successfully written<br /> * to persistent storage.<br /> */<br /> boolean commit();<br /> }</p><p> /**<br /> * Retrieve all values from the preferences.<br /> *<br /> * @return Returns a map containing a list of pairs key/value representing<br /> * the preferences.<br /> *<br /> * @throws NullPointerException<br /> */<br /> Map<String, ?> getAll();</p><p> /**<br /> * Retrieve a String value from the preferences.<br /> *<br /> * @param key The name of the preference to retrieve.<br /> * @param defValue Value to return if this preference does not exist.<br /> *<br /> * @return Returns the preference value if it exists, or defValue. Throws<br /> * ClassCastException if there is a preference with this name that is not<br /> * a String.<br /> *<br /> * @throws ClassCastException<br /> */<br /> String getString(String key, String defValue);</p><p> /**<br /> * Retrieve an int value from the preferences.<br /> *<br /> * @param key The name of the preference to retrieve.<br /> * @param defValue Value to return if this preference does not exist.<br /> *<br /> * @return Returns the preference value if it exists, or defValue. Throws<br /> * ClassCastException if there is a preference with this name that is not<br /> * an int.<br /> *<br /> * @throws ClassCastException<br /> */<br /> int getInt(String key, int defValue);</p><p> /**<br /> * Retrieve a long value from the preferences.<br /> *<br /> * @param key The name of the preference to retrieve.<br /> * @param defValue Value to return if this preference does not exist.<br /> *<br /> * @return Returns the preference value if it exists, or defValue. Throws<br /> * ClassCastException if there is a preference with this name that is not<br /> * a long.<br /> *<br /> * @throws ClassCastException<br /> */<br /> long getLong(String key, long defValue);</p><p> /**<br /> * Retrieve a float value from the preferences.<br /> *<br /> * @param key The name of the preference to retrieve.<br /> * @param defValue Value to return if this preference does not exist.<br /> *<br /> * @return Returns the preference value if it exists, or defValue. Throws<br /> * ClassCastException if there is a preference with this name that is not<br /> * a float.<br /> *<br /> * @throws ClassCastException<br /> */<br /> float getFloat(String key, float defValue);</p><p> /**<br /> * Retrieve a boolean value from the preferences.<br /> *<br /> * @param key The name of the preference to retrieve.<br /> * @param defValue Value to return if this preference does not exist.<br /> *<br /> * @return Returns the preference value if it exists, or defValue. Throws<br /> * ClassCastException if there is a preference with this name that is not<br /> * a boolean.<br /> *<br /> * @throws ClassCastException<br /> */<br /> boolean getBoolean(String key, boolean defValue);</p><p> /**<br /> * Checks whether the preferences contains a preference.<br /> *<br /> * @param key The name of the preference to check.<br /> * @return Returns true if the preference exists in the preferences,<br /> * otherwise false.<br /> */<br /> boolean contains(String key);</p><p> /**<br /> * Create a new Editor for these preferences, through which you can make<br /> * modifications to the data in the preferences and atomically commit those<br /> * changes back to the SharedPreferences object.<br /> *<br /> * <p>Note that you <em>must</em> call {@link Editor#commit} to have any<br /> * changes you perform in the Editor actually show up in the<br /> * SharedPreferences.<br /> *<br /> * @return Returns a new instance of the {@link Editor} interface, allowing<br /> * you to modify the values in this SharedPreferences object.<br /> */<br /> Editor edit();</p><p> /**<br /> * Registers a callback to be invoked when a change happens to a preference.<br /> *<br /> * @param listener The callback that will run.<br /> * @see #unregisterOnSharedPreferenceChangeListener<br /> */<br /> void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener);</p><p> /**<br /> * Unregisters a previous callback.<br /> *<br /> * @param listener The callback that should be unregistered.<br /> * @see #registerOnSharedPreferenceChangeListener<br /> */<br /> void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener);<br />}<br />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.