SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中 重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成,它提供了Android平台常规的Long长 整形、Int整形、String字符串型的保存,这些信息以XML文件的形式保存在 /data/data/PACKAGE_NAME /shared_prefs 目录下。
SharedPreferencespre = getSharedPreferences("soft",Context.MODE_WORLD_READABLE);
在这里我们可以调用 activity 为我们提供的方法,这个方法有两个参数:
1). 文件名。 在这里要特别注意。 因为在Android 中已经确定了SharedPreferences 是以 xm l形式保存,所以,在填写文件名参数时,不要给定 ” .xml ”后缀, android 会自动添加 。它是采用键值对的形式保存参数。 当你需要获得某个参数值时, 按照参数的键索引即可。
2). 第二个可以理解为创建模式和之前的文件存储的模式是一样的。
Context. MODE_PRIVATE
Context.MODE_APPEND MODE_APPEND
Context.MODE_WORLD_READABLE
Context.MODE_WORLD_WRITEABLE
实验步骤
界面:
1、 资源
2、 布局
4、 添加读取功能
资源添加
<string name="read_text">读取</string>
布局修改为
view plaincopy to clipboardprint?
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:stretchColumns="*">
<TableRow >
<Button
android:id="@+id/saveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="@string/save_text" />
<Button
android:id="@+id/readBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="@string/read_text" />
</TableRow>
</TableLayout>
代码修改为
view plaincopy to clipboardprint?
public void onClick(View v) {
SharedPreferences sp = getSharedPreferences("myOption",
MODE_PRIVATE);
String name="无名氏";
int age = -1;
switch (v.getId()) {
case R.id.saveBtn:
name = nameEt.getText().toString().trim();
age = Integer.valueOf(ageEt.getText().toString().trim());
Editor editor = sp.edit();
editor.putString("name", name);
editor.putInt("age", age);
editor.commit();
break;
case R.id.readBtn:
name = sp.getString("name", "无名氏");
age = sp.getInt("age", -1);
Toast.makeText(this,
"姓名: "+name+ " 年龄: " +String.valueOf(age),
Toast.LENGTH_SHORT).show();
break;
}
}