码迷,mamicode.com
首页 > 移动开发 > 详细

【Android应用开发技术:数据存储】SharedPreferences

时间:2015-07-30 14:53:27      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

作者:郭孝星
微博:郭孝星的新浪微博
邮箱:allenwells@163.com
博客: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

标签:

原文地址:http://blog.csdn.net/allenwells/article/details/47149423

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!