全屏浏览
缩小浏览
回到页首

android基础---->SharedPreferences的使用

  SharedPreferences 还支持多种不同的数据类型存储,如果存储的数据类型是整型,那么读取出来的数据也是整型的,存储的数据是一个字符串,读取出来的数据仍然是字符串。这样你应该就能明显地感觉到,使用SharedPreferences 来进行数据持久化要比使用文件方便很多。

 

目录导航

  1.  sharedPreferences简要的说明
  2.  sharedPreferences的使用步骤
  3.  sharedPreferences的项目结构
  4.  sharedPreferences的项目代码
  5.  sharedPreferences的实现原理
  6.  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()方法得到数据

 

项目结构

 

项目代码

一、 AndroidManifest.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.linux.sharedpreferencestest">
 4 
 5     <application
 6         android:allowBackup="true"
 7         android:icon="@mipmap/ic_launcher"
 8         android:label="@string/app_name"
 9         android:supportsRtl="true"
10         android:theme="@style/AppTheme">
11         <activity android:name=".MainActivity">
12             <intent-filter>
13                 <action android:name="android.intent.action.MAIN" />
14 
15                 <category android:name="android.intent.category.LAUNCHER" />
16             </intent-filter>
17         </activity>
18     </application>
19 
20 </manifest>
View Code

二、 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

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:orientation="vertical"
 7     tools:context="com.example.linux.sharedpreferencestest.MainActivity">
 8 
 9     <TextView
10         android:id="@+id/textView"
11         android:layout_width="wrap_content"
12         android:layout_height="wrap_content"
13         android:text="Hello World!" />
14 
15     <Button
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:onClick="write"
19         android:text="writeToShare" />
20 
21     <Button
22         android:layout_width="wrap_content"
23         android:layout_height="wrap_content"
24         android:onClick="read"
25         android:text="readFromShare" />
26 </LinearLayout>
View Code

 

实现原理

  • 数据的存储:
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

    

    2.  SharedPreferences.Editor editor = preferences.edit();生成一个EditorImpl,里面有一个hashmap,代码putXXX()都是存放在这个map里面的:具体代码见上述数据的存储:

       3.  editor.commit();提交到内存,并且比较modifymapmap,更新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);
  • 原理说明:读取:
  1.  SharedPreferences preferences = this.getPreferences(Context.MODE_PRIVATE);得到上述的文件,解析成键值对存放在map当中
  2.  String name = preferences.getString(key,  defvlue);实际上是执行:String v = (String)mMap.get(key);  return v != null ? v : defValue;
  • 文件位置:  /data/data/<package name>/shared_prefs/文件名.xml:

 

友情链接:

 

posted @ 2016-03-04 13:04  huhx  阅读(1726)  评论(0编辑  收藏  举报