sharepreference专门用于保存用户的偏好设置参数,它是一个轻量级的存储类,特别适合用于保存软件配置参数
SharedPreferences保存数据其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs/xxx.xml目录下
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名" />
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="年龄" />
<EditText
android:id="@+id/age"
android:layout_width="fill_parent"
android:numeric="integer"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="save"
android:text="保存" />
</LinearLayout>
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name_text = (EditText) this.findViewById(R.id.name);
age_text = (EditText) this.findViewById(R.id.age);
service = new preferencesService(this);
//下面回显参数
Map<String, String> params = service.getPreference();
name_text.setText(params.get("name"));
age_text.setText(params.get("age"));
}
public void save(View v){
String name = name_text.getText().toString();
String age = age_text.getText().toString();
service.save(name,age);
Toast.makeText(getApplicationContext(), "保存完成", 1).show();
}
}
preferencesService业务类
public class preferencesService {
private Context context;
public preferencesService(Context context) {
this.context = context;
}
//保存参数
public void save(String name, String age) {
<span style="white-space:pre"> //参数1:指定该文件的名称,不用带后缀,参数2:指定文件的操作模式
<span style="white-space:pre"> </span>Editor editor = preference.edit();<span style="white-space:pre"> </span>//得到保存数据的编辑器</span><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">editor存储对象采用key-value键值对进行存放</span>
SharedPreferences preference = context.getSharedPreferences("params", context.MODE_PRIVATE);
Editor editor = preference.edit(); //得到保存数据的编辑器
editor.putString("name", name);<span style="white-space:pre"> </span>//editor存储对象采用key-value键值对进行存放
editor.putInt("age", new Integer(age));
editor.commit(); //提交数据
}
//获取配置参数
public Map<String,String> getPreference(){
Map<String,String> params = new HashMap<String, String>();
SharedPreferences preference = context.getSharedPreferences("itcase", context.MODE_PRIVATE);
params.put("name", preference.getString("name", ""));//获取参数保存到集合里面,参数2:为缺省值,如果preference中不存在该key,将返回缺省值
params.put("age", String.valueOf(preference.getInt("age", 0)));
return params;
}
}