SharedPreferences

今天做了对SharedPreferences做了简单的测试,并分享 sharePreferences 使用:
例子1.基本的存放和取得。
SharedPreferences share = getSharedPreferences("userPhoneNum",MODE_WORLD_WRITEABLE);
 
  //可以
  Editor edit = share.edit();
  edit.putString("name", "dyc");
  edit.putBoolean("flag", true);
  edit.commit();
读成功!
    System.out.println(share.getString("name", ""));
  System.out.println(share.getBoolean("flag", false));
 

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">dyc</string>
<boolean name="flag" value="true" />
</map>

例2:
SharedPreferences share = getSharedPreferences("userPhoneNum",0);
 
  //可以
  Editor edit = share.edit();
  edit.putString("name", "yancheng");
  edit.putString("company", "funo");
  edit.putBoolean("flag", true);
  edit.commit();
 
  //加入成功
  SharedPreferences.Editor localEditor = share.edit();
  localEditor.putBoolean("flag", false);
  localEditor.putString("name", "you");
  localEditor.putString("name1", "IBM");
  localEditor.commit();


  得到share文件 :
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name1">IBM</string>
<string name="name">you</string>
<string name="company">funo</string>
<boolean name="flag" value="false" />
</map>
显然在这里看到了覆盖的效果。

例3.

SharedPreferences share = getSharedPreferences("userPhoneNum",MODE_WORLD_READABLE);
 
  //可以
  Editor edit = share.edit();
  edit.putString("name", "dyc");
  edit.putBoolean("flag", true);
  edit.commit();
读成功!
    System.out.println(share.getString("name", ""));
  System.out.println(share.getBoolean("flag", false));
 

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">dyc</string>
<boolean name="flag" value="true" />
</map>
只是变化了mode类型。根据字面意思就可以了解它的作用了。
例4.
  SharedPreferences share = getSharedPreferences("userPhoneNum",MODE_WORLD_READABLE);
 
  //可以
  Editor edit = share.edit();
  edit.putString("name", "yancheng");
  edit.putString("company", "funo");
  edit.putBoolean("flag", true);
  edit.commit();
 
  //加入成功
  SharedPreferences.Editor localEditor = share.edit();
  localEditor.putBoolean("flag", false);
  localEditor.putString("name", "you");
  localEditor.putString("name1", "IBM");
  //这里加入这个方法
  localEditor.clear();
  localEditor.commit();
 

  结果:
 
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name1">IBM</string>
<boolean name="flag" value="false" />
<string name="name">you</string>
</map>
这里想和例2做个比较来说明。SharedPreferences的生成点实在commit时完成。
所以使用clear清除的是上次commit的内容。暂时先记录到这里。

你可能感兴趣的:(mode)