Java SharedPreferences的使用

来源:互联网 发布:山海关 知乎 编辑:程序博客网 时间:2024/05/23 19:53

SharedPreferences 是以键值对来存储应用程序的配置信息的一种方式,它只能存储基本数据类型。一个程序的配置文件仅可以在本应用程序中使用,或者说只能在同一个包内使用,不 能在不同的包之间使用。 实际上SharedPreferences是采用了XML格式将数据存储到设备中,在DDMS中的File Explorer中的/data/data/<package name>/shares_prefs下。


以下表格为获取SharedPreferences对象的两个方法:

返回值

函数

备注

SharedPreferences

Context.getSharedPreferences(String name,int mode)

name 为本组件的配置文件名(如果想要与本应用程序的其他组件共享此配置文件,可以用这个名字来检索到这个配置文件)。

mode 为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE。

SharedPreferences

Activity.getPreferences(int mode)

配置文件仅可以被调用的Activity使用。

mode 为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE。

如 果要读取配置文件信息,只需要直接使用SharedPreferences对象的getXXX()方法即可,而如果要写入配置信息,则必须先调用 SharedPreferences对象的edit()方法,使其处于可编辑状态,然后再调用putXXX()方法写入配置信息,最后调用 commit()方法提交更改后的配置文件。


既然它是用来保存数据的 那么一点下面问题:

1. 如何创建

2. 如何加入数据

3. 如何取出数据



package cn.edu.wtu;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.os.Bundle;import android.widget.TextView;public class PreferenceDemo extends Activity {    /** Called when the activity is first created. */  public final static String COLUMN_NAME ="name"; public final static String COLUMN_MOBILE ="mobile"; SharedPreferencesHelper sp;     @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);//        setContentView(R.layout.main);        //存储文件的名字是contacts.xml,在eclipse中的DDMS的fileexplore页下的data/data/包名/shared_prefs下        sp = new SharedPreferencesHelper(this, "contacts");                //1. to store some value        sp.putValue(COLUMN_NAME, "Gryphone");        sp.putValue(COLUMN_MOBILE, "123456789");                        //2. to fetch the value        String name = sp.getValue(COLUMN_NAME);        String mobile = sp.getValue(COLUMN_MOBILE);                TextView tv = new TextView(this);        tv.setText("NAME:"+ name + "/n" + "MOBILE:" + mobile);                setContentView(tv);    }        class SharedPreferencesHelper{          SharedPreferences sp;     SharedPreferences.Editor edit;     Context context;          public SharedPreferencesHelper(Context context,String name){            this.context=context;      sp=context.getSharedPreferences(name,0);      edit=sp.edit();     }          public void putValue(String key,String value){            edit.putString(key,value);      edit.commit();           }     public String getValue(String key){            return sp.getString(key,null);     }    }}


另外再补充SharePreferences的getBoolean方法:

//getBoolean源码//Boolean v = (Boolean)mMap.get(key);//      return (v != null) ? v : defValue;//其实SharedPreference的实现也是通过Map来的//第一次启动时,KeyFirstUse没有值,为null,所以进入else分支if (prefs.getBoolean(CfgInf.KeyFirstUse, false)) {} else {Editor editor = prefs.edit(); editor.putBoolean(CfgInf.KeyFirstUse, true);// 设置不是第一次启动,之后就只进入if分支}




0 0
原创粉丝点击