SharedPreferences 还支持多种不同的数据类型存储,如果存储的数据类型是整型,那么读取出来的数据也是整型的,存储的数据是一个字符串,读取出来的数据仍然是字符串。这样你应该就能明显地感觉到,使用SharedPreferences 来进行数据持久化要比使用文件方便很多。
目录导航
- sharedPreferences简要的说明
- sharedPreferences的使用步骤
- sharedPreferences的项目结构
- sharedPreferences的项目代码
- sharedPreferences的实现原理
- sharedPreferences的友情链接
简单说明
1. SharedPreferences是使用键值对的方式来存储数据的.
2. SharedPreferences保存的数据将持续整个用户会话,即使你的应用程序被杀掉(killed),直到应用程序卸载
3. SharedPreferences有三种模式:
- Context.MODE_PRIVATE:别的应用不能访问得到SharedPreferences对象
- Context.MODE_WORLD_READABLE:别的应用可以访问,并且是可以读取SharedPreferences中的数据,但不能写入数据
- Context.MODE_WORLD_WRITEABLE:别的应用可以访问,可以在SharedPreferences中写入修改数据
4. Android提供了三种方式得到SharedPreferences 对象:本质上都是调用Context 类中的getSharedPreferences()方法:
- Context类中的getSharedPreferences():两个参数,第一个指定生成文件的名称,第一个是操作模式。这样可以在一个Activity中创建多个SharedPreferences的文件
- Activity类中的getPreferences():一个参数,操作模式。使用当前活动的类名作为文件的名称
- PreferenceManager类中的getDefaultSharedPreferences():一个Context参数,使用当前应用程序的包名作为前缀来命名SharedPreferences文件
使用步骤
1. 向SharedPreferences中写入数据,分为四步:
- 通过上述说明,得到SharedPreferences对象
- 调用SharedPreferences 对象的edit()方法来获取一个SharedPreferences.Editor 对象
- 向SharedPreferences.Editor 对象中添加数据
- 调用commit()方法将添加的数据提交,从而完成数据存储操作
2. 向SharedPreferences中读取数据,分为两步:
- 通过上述说明,得到SharedPreferences对象
- 调用SharedPreferences的getXXX()方法得到数据
项目结构
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWsAAAD5CAIAAABu/YPTAAAX8ElEQVR4nO2dz48bVYLH/VfsbS8c9rSXPeyKknYRyoA2WkROucxwWaFVHeAUobQG2E2DtIIZZiihHSmZAVagWS1Z1LHd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oH9y/QN8s4773Q6nUwVXc+kZjOInIWqR41aZx0ntgZQeKZpkIWFhe3tbYeKrp/mZpyD+PqpT6es48TWAArP/vlO6li/DzLehQbLFti3FNIgkweDAFiBQYxgEAArMAgAuINBAMAdDAIA7mAQAHAHgwCAOxgEANzBIADgTiENQtIyQE7YJwYZq0QaPt//ArCDpGUdDAJgy/Sv7s9f0jIGAbBl+gbJX9IyBgGwJRcG2ZOkZenHYOIbhmDkgUHEC+Kki+PizGSpQeI/oHzkyCATT1qOI4GEbGVDMPJwg4jBQoO9XHwLZSVHBtm7pGV5wGvTh6EGiecf4jSkt5ffu4PSkReD7EnScl8hzcAT5iJ6MHKaQRJF0XMRHoESMX2D7GHSchg2A8/z/YFAEoKRRYOIqol/MkY4I9IvGZjOlwDse0qVtBxqSenGYOT4s5jobuFe81lTfpAOysn++U7qWJOWAcCKQhoEAHICBgEAdzAIALiDQQDAHQwCAO5gEABw5/8BFg89JackK/8AAAAASUVORK5CYII=" alt="" />
项目代码
一、 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.linux.sharedpreferencestest"> <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> </manifest>
二、 MainActivity.java:
在oncreate方法中初始化一些组件:
private TextView textView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
}
创建sharedpreference,并且写入数据:
// 在share preference中写入数据
public void write(View view) {
//PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences preferences = this.getPreferences(Context.MODE_PRIVATE);
//SharedPreferences preferences = this.getSharedPreferences("Linux", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); Set<String> stringSet = new HashSet<>();
stringSet.add("Huhx");
stringSet.add("Tomhu");
editor.putInt("int", 3);
editor.putString("name", "Linux");
editor.putStringSet("set", stringSet); editor.commit();
Toast.makeText(MainActivity.this, "write to sharde preference success!", Toast.LENGTH_SHORT).show();
}
创建sharedpreference,并且读取数据:
//在share preference中读取数据
public void read(View view) {
SharedPreferences preferences = this.getPreferences(Context.MODE_PRIVATE);
int intData = preferences.getInt("int", 0);
String name = preferences.getString("name", "无名");
Set<String> set = preferences.getStringSet("set", null); StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("int: " + intData + "\n");
stringBuffer.append("name: " + name + "\n");
int length = set == null ? 0 : set.size();
stringBuffer.append("set size: " + length + "\n"); textView.setText(stringBuffer.toString());
Toast.makeText(MainActivity.this, "read from shared preference success!", Toast.LENGTH_SHORT).show();
}
三、 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.linux.sharedpreferencestest.MainActivity"> <TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="write"
android:text="writeToShare" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="read"
android:text="readFromShare" />
</LinearLayout>
实现原理
- 数据的存储:
public final class EditorImpl implements Editor {
private final Map<String, Object> mModified = Maps.newHashMap();
private boolean mClear = false; public Editor putString(String key, @Nullable String value) {
synchronized (this) {
mModified.put(key, value);
return this;
}
}
}
- 数据的读取:
@Nullable
public String getString(String key, @Nullable String defValue) {
synchronized (this) {
awaitLoadedLocked();
String v = (String)mMap.get(key);
return v != null ? v : defValue;
}
}
- 数据文件:
SharedPreferencesImpl(File file, int mode) {
mFile = file;
mBackupFile = makeBackupFile(file); // 生成bak备份文件
mMode = mode;
mLoaded = false;
mMap = null;
startLoadFromDisk(); //命名文件,解析xml文件,并且将键值对存放到Map中
}
- 原理说明:写入:
1. SharedPreferences preferences = this.getPreferences(Context.MODE_PRIVATE);第一次执行的时候,android在/data/data/<package name>/shared_prefs创建了一个xml文件和一个Modifymap:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAxYAAABBCAIAAADDv6UiAAAY0klEQVR4nO2d34vdxtnH9WdF/4FDqJ2WkNJS8DqNFZM0xBhKHdNa58K+rC4CFoVNvS52i2trQ4qxQmjeGMVQ0k2hF44jLAKG4iXx8U32wpAY4vNeSBo9z8wz0uisdH7sfj/sxdk5M888M6MZfc8zc468f/334ebm5r/++xB/+MMf/vCHP/zhD3+Of9577723ubn5HgAAAAAAcMb79ttvNzc3ZwAAAAAAwBlIKAAAAACA3kBCAQAAAAD0BhIKAAAAAKA3A0uo/4tf6/wbqi4AAAAAgGWxahIqTTw/K3haEcVm4ojkSRhn01W2Pc3icDKZJPkQLq0KeRIerAYBAAA40AgS6qOPPvruu+/mM7cmEipPQqVk8iQMJ5MJUSSLkVCVDOJVOzHN4pUSG9MsnqMVBoaEmmZx2HSRPiTkXVKsGs2QmVKJ1IaQmCdNdTy5O6fqBMHhPNE7R3LeUntVXDVqmsXhSg0/AAAcVgQJtb29vb29/dlnn/3www99zc0loYrM95K0fC1JqMFpbtZ50tyOpllcvlyYhKprmWZxnxrH9G9OhnCJSShTKORJSFLIwDW9p0ZQfpukioliK9xzaoWaisI4SZjotXon2JRSEa8DAIBVwCqhtre3P/jgg3v37o3vw6IlVCNeiIwhLFxC9azy4EsoZS5PyuhLkoRJTsNvtEKLylCyqtEb9T9iomjIPaetkJAgO28RcEI9cioAAIDF0iahSm7durW7u+torn8UKk08b+J5E88L/ehxKaGioEoJ0tms3MgLqg/tkV+9VadQisj3OH4kyDFyB6JRKEWehHGW1bsn7Aaqbb6Ut8Y8CUMaqTA2nppEskcjSqhug2q7J2zu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7gOiAAAAAElFTkSuQmCC" alt="" />
2. SharedPreferences.Editor editor = preferences.edit();生成一个EditorImpl,里面有一个hashmap,代码putXXX()都是存放在这个map里面的:具体代码见上述数据的存储:
3. editor.commit();提交到内存,并且比较modifymap和map,更新map。然后将内存中的内容写入文件当中
for (Map.Entry<String, Object> e : mModified.entrySet()) {
String k = e.getKey();
Object v = e.getValue();
if (v == this || v == null) {
if (!mMap.containsKey(k)) {
continue;
}
mMap.remove(k);
} else {
if (mMap.containsKey(k)) {
Object existingValue = mMap.get(k);
if (existingValue != null && existingValue.equals(v)) {
continue;
}
}
mMap.put(k, v);
- 原理说明:读取:
- SharedPreferences preferences = this.getPreferences(Context.MODE_PRIVATE);得到上述的文件,解析成键值对存放在map当中
- String name = preferences.getString(key, defvlue);实际上是执行:String v = (String)mMap.get(key); return v != null ? v : defValue;
- 文件位置: /data/data/<package name>/shared_prefs/文件名.xml: