SharedPreferences sps= getSharedPreferences("share", MODE_PRIVATE); //存储数据 SharedPreferences.Editor editor = sps.edit(); editor.putString("name", "Mr Lee"); editor.putInt("age", 30); editor.putBoolean("married", true); editor.putFloat("weight", 100f); editor.commit();
SharedPreferences sps= getSharedPreferences("share", MODE_PRIVATE); //读取数据,注意get方法的第二个参数表示默认值 String name = sps.getString("name", ""); int age = sps.getInt("age", 0); boolean married = sps.getBoolean("married", false); float weight = sps.getFloat("weight", 0);
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="name">Mr Lee</string> <int name="age" value="30" /> <boolean name="married" value="true" /> <float name="weight" value="100.0" /> </map>
上面可以看到,SharedPreferences文件中的数据都是明文存储,所以共享变量方式不适合存储一些敏感的业务数据,如果确有必要在这里存储数据,那么一定要将数据加密后方可使用。
点此查看Android开发笔记的完整目录