1 主Acitvity
package com.EX054;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
/*
* to access from: data/data/com.android.SharedPreferences/share_prefs
*/
public class EX054use extends Activity {
public final static String COLUMN_NAME ="名字";
public final static String COLUMN_MOBILE ="电话";
EX054Helper sp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
sp = new EX054Helper(this, "contacts");
//1. to store some value
sp.putValue(COLUMN_NAME, "莉莉");
sp.putValue(COLUMN_MOBILE, "150XXXXXXXX");
//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);
}
}
2 封装SharedPreferences辅助类
package com.EX054;
import android.content.Context;
import android.content.SharedPreferences;
public class EX054Helper {
SharedPreferences sp;
SharedPreferences.Editor editor;
Context context;
public EX054Helper(Context c,String name){
context = c;
sp = context.getSharedPreferences(name, 0);
editor = sp.edit();
}
public void putValue(String key, String value){
editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public String getValue(String key){
return sp.getString(key, null);
}
}
3 没有layout页面,这个用不上,就用默认的就行了,结果图如下
3 其实上面类封装的有点恶心:把简单问题搞复杂了:看下面的方法:简介明了
Preferences是一个较轻量级的存储数据的方法,具体使用方法:
在A中保存值:
SharedPreferences.Editor sharedata = getSharedPreferences("data", 0).edit();
sharedata.putString("name","shenrenkui");
sharedata.commit();
在B中取值:
SharedPreferences sharedata = getSharedPreferences("data", 0);
String data = sharedata.getString("name", null);
Log.i(TAG,"data="+data);
注意:Context.getSharedPreferences(Stringname,inttype)的参数更我们在创建数据的时候的数据权限属性是一样的,存储和取值的过程这有点像HashMap但是比HashMap更具人性化,getXXX(Objectkey,ObjectdefualtReturnValue),第二个参数是当你所要的key对应没有时候返回的值。这就省去了很多逻辑判断。