android之SharedPreferences进行数据存储

首先我们来介绍一下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. Note: currently this class does not support use across multiple processes. This will be added later.

翻译如下:

       SharedPreferences接口一般用来访问或修改由方法getSharedPreferences(String,int)返回的设置信息。这里的设置信息都是单例唯一的,这就意味着改设置信息会被所以安装了该APK应用的客户端(手机)所共享。如果我们要想修改这些设置信息,我们则必须要通过SharedPreferences.Editor对象进行修改,至于为什么一定要获取这个Editor对象之后才可以修改呢,原因是这样的,我们前面已经说了,改配置信息会被所有的客户端共享,那就意味着同一时刻可能有好几个客户端要对配置信息中的值进行修改,这很容易出现数据修改混乱的问题,这里通过获取SharedPreferences.Editor对象就是为了保证数据的一致性。注意,到目前为止,SharedPreferences是不支持多进程的,该功能处于待添加状态。

      我们再来看看,该接口中主要的方法有哪些:

《android之SharedPreferences进行数据存储》

 

《android之SharedPreferences进行数据存储》

           

     SharedPreferences包含两个内部类,SharedPreferences.Editor和SharedPreferences.OnSharedPreferencesChangeListener;其中Editor主要在对属性设置进行修改时使用,而OnSharedPreferencesChangeListener则是在属性被修改时触发的一个事件,我们可以在里面做一些额外的动作,如根据新的属性值去触发一些页面的改变了,等等……

 

     

     至于其他的方法,都很简单,一看方法名就知道啥意思了,我就不详细介绍了。现在给大家贴一个应用的例子:

 

先上图:《android之SharedPreferences进行数据存储》

然后是main.xml

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

activity的代码:

package cn.com.sharedPreferencesTest; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class SharedPreferencesActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); saveSharedPreferences(); readSharedPreferences(); } /** * @author chenzheng_java * @description 创建并保存一些设置信息 * @since 2011/03/05 */ private void saveSharedPreferences(){ /* * getSharedPreferences(String name,int mode)方法是在Context中定义的抽象方法,在ContextWrapper中进行了具体实现, * 该方法会根据用户传递的名称和写入类型创建一个SharedPreferences对象进行返回。 * 在Activity中,还有一个方法可以回去SharedPreferences对象,这个方法就是SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); * 改方法在Activity中定义并实现,这里没有name参数是因为该方法默认将当前Activity的类名作为name属性(这里的类名并不包含包路径哦) * */ SharedPreferences sharedPreferences = getSharedPreferences(“preferences”, MODE_PRIVATE); //存储数据 SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(“name”, “蔡依林”); editor.putInt(“age”, 31); Boolean b = editor.commit(); if(b){ Log.i(“通知:”, “保存成功!”); }else{ Log.i(“通知”, “保存失败!”); } } /** * @author chenzheng_java * @description 读取我们添加到SharedPreference对象中的数据 * @since 2011/03/05 */ private void readSharedPreferences(){ String result = “美女信息:/n” ; SharedPreferences sharedPreferences = this.getSharedPreferences(“preferences”, MODE_PRIVATE); result+=” 姓名 “+sharedPreferences.getString(“name”, “暂时没有人”); result+=” 年龄”+sharedPreferences.getInt(“age”, -1); TextView textView = (TextView)findViewById(R.id.textView); textView.setText(result); } }

其他的都为默认。

———————————————————————

最后了,说点废话

SharedPreferences实际上是按照键值对的方式进行数据存储的,如果同一个key被设置了两次值,那么后来的值将会覆盖掉前面的值。实际上,SharedPreferences在后台是使用XML文件的格式进行存储数据的,其存储的目录为/data/data/应用包名称/shared_prefs。

如:

<?xml version=’1.0′ encoding=’utf-8′ standalone=’yes’ ?> <map> <int name=”age” value=”31″ /> <string name=”name”>蔡依林</string> </map>

而且SharedPreferences对象对于存储值的格式是有严格要求的,从方法中我们可以看到,只能存储String/int/long/Float/Boolean几种类型的数据。

————————————————————————————

小技巧:如果我们在当前的activity中想访问另一个activity(如cn.com.abc.activityTest)的SharedPreferences对象,我们应该如何获取呢?

  应该如下获取

 

// 获取包含cn.com.abc.activityTest的那个context对象,然后通过context对象来获取,注意这里的mode必须为Context.MODE_WORLD_READABLE Context otherAppContext = createPackageContext(“cn.com.abc.activityTest”, Context.CONTEXT_IGNORE_SECURITY); SharedPreferences sharedPreferences = otherAppContext.getSharedPreferences(“preferences”, Context.MODE_WORLD_READABLE);  

————————————————————–

最后粘贴上SharedPreferences的源码,方便查阅。

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

    原文作者:chenzheng_java
    原文地址: https://blog.csdn.net/chenzheng_java/article/details/6225168
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞