SharedPreferences

从javaeye网站上整理得来

 

 

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

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);
     }
    }
}

 

 

 

 

 

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值