您的位置:首页 > 移动开发 > Android开发

【Android笔记 九】Android Sharedpreferences实现用户偏好存储

2011-11-04 23:08 399 查看
在开发应用程序的过程中,有时候我们需要记录用户的偏好,或者用户名密码之类。这就要涉及到数据的存储,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

nameDesired 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的时候(用于编辑偏好文件,下面会介绍)会自动创建。

modeOperating 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方法就好了。

不多说了,奉上一段自己临时写的一段非常简单的代码,与大家分享



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只是一个接口,我并没有找到它的实现,网上也没有相应的解答,希望了解的朋友能及时的联系我,交流一下,谢谢,十一点了,实验室没人了,准备回去睡觉~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: