适用于少量数据且数据格式简单的存储情况,都是普通的字符串、标量类型的值等,如应用程序的各种配置信息。对于这种数据,Android提供了SharedPreferences进行保存。
下面是SharedPreferences简单的读写程序。
public class SharedPreferencesTest extends Activity {
SharedPreferences sp;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button read = (Button) findViewById(R.id.read);
Button write = (Button) findViewById(R.id.write);
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//读取时间信息
String result = readData(SharedPreferencesTest.this,"time");
//用Toast显示
Toast.makeText(SharedPreferencesTest.this,result,5000).show();
}
});
write.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//设置存入时间的格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "+"hh:mm:ss");
String name = "time";
String value = sdf.format(new Date()); //value值设置为当前时间
writeData(SharedPreferencesTest.this,name,value);
Toast.makeText(SharedPreferencesTest.this,"写入time成功",5000).show();
}
});
}
//写入数据
private void writeData(Context context, String name, String value) {
sp = context.getSharedPreferences("lune", MODE_PRIVATE);
editor = sp.edit(); //添加一个编辑
editor.putString(name, value); //写入键值对 name-s;
editor.commit(); //提交修改
}
//读取数据
private String readData(Context context, String name) {
sp = context.getSharedPreferences("lune", MODE_PRIVATE);
String result = sp.getString(name, null); //第一个参数为key,第二个参数为默认值,若找不到value,则返回默认值
if (result == null) {
result = "此数据不存在";
}
return result;
}
}
界面只有两个按钮,下面是main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="写入数据"
android:id="@+id/write"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读取数据"
android:id="@+id/read"
android:layout_gravity="center_horizontal" />
</LinearLayout>
运行结果如下图: