SharedPreferences详解

来源:互联网 发布:c语言void的应用 编辑:程序博客网 时间:2024/06/14 05:23

一、简介
SharedPreferences作为Android存储数据方式之一,是一种轻型的数据存储方式,基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。
主要特点是:
1. 只支持Java基本数据类型,不支持自定义数据类型;
2. 应用内数据共享;
3. 使用简单.

二、存储位置
在/data/data/<包名>/shared_prefs目录下。

三、操作数据
SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。
具体操作过程:

1、根据Context获取SharedPreferences对象
2、利用edit()方法获取Editor对象。
3、通过Editor对象存储key-value键值对数据。
4、通过commit()方法提交数据。
四、实例代码

public class SpDemoActivity extends Activity {    String LOG_TAG = "SpDemoActivity";    @Override      public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         //获取SharedPreferences对象         Context ct = SpDemoActivity.this;                SharedPreferences sp = ct.getSharedPreferences("MY_SP", MODE_PRIVATE);        //存入数据        Editor editor = sp.edit();        editor.putString("NAME", "测试姓名");        editor.putInt("AGE", 20);        editor.putBoolean("HAS_RIGHT", true);        editor.commit();        //返回STRING_KEY的值,定义key值错误或者此key无对应value值的话返回""        Log.d(LOG_TAG, sp.getString("NAME", ""));        //如果OTHER_KEY不存在,定义key值错误或者此key无对应value值的返回值为"other"        Log.d(LOG_TAG, sp.getString("NAME", "other"));     }

注:在私有目录下生成一个MY_SP.xml文件,里面采用键值对的形式存储数据。

<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="NAME">测试姓名</string> <int name="AGE" value="20" /> <boolean name="HAS_RIGHT" value="true" /> </map>

五、方法详解

1、getSharedPreferences(String name, int mode)
参数1:name, 存储时的名称,比如这里的”NAME”;
参数2:mode,打开方式,一般都用Activity.MODE_PRIVATE、MODE_PRIVATE

2、registerOnSharedPreferenceChangeListener(
SharedPreferences.OnSharedPreferenceChangeListener listener)
参数1:listener,注册一个当preference发生改变时被调用的回调函数

3、unregisterOnSharedPreferenceChangeListener(
SharedPreferences.OnSharedPreferenceChangeListener listener):
参数1:listener,删除当前回调函数

4、SharedPreferences.Editor接口
用于修改SharedPreferences对象的内容,所有更改都是在编辑器所做的批处理,而不是复制回原来的SharedPreferences或持久化存储,直到你调用commit(),才会永久存储。
方法说明:
clear():清除内容。
commit():提交修改
remove(String key):删除preference
使用举例:
4.1 存数据
步骤如下:
(1)获取SharedPreferences实例。
(2)通过SharedPreferences的实例获取Editor实例。注:SharedPreferences本身并没有提供写入数据的能力,而是通过其内部类SharedPreferences.Editor来实现。
(3)调用Editor的write方法,切记后面还要commit。
示例代码如下:

SharedPreferences sp = getSharedPreferences("MY_SP", Context.MODE_PRIVATE);sp.edit().putString("NAME", "小张").putInt("AGE", 11).commit();

或者

SharedPreferences sp = getSharedPreferences("MY_SP", Context.MODE_PRIVATE);Editor editor = sp.edit();editor.putString("NAME", "小张");editor.putInt("AGE", 11);editor.commit();

切记不要写成下面的形式,会导致数据无法存储

SharedPreferences sp = getSharedPreferences("MY_SP", Context.MODE_PRIVATE);sp.edit().putString("NAME", "小张");sp.edit().putInt("AGE", 11);sp.edit().commit();

为什么这种方式无法存储,因为sp.edit()每次都会返回一个新的Editor对象,Editor的实现类EditorImpl里面会有一个缓存的Map,最后commit的时候先将缓存里面的Map写入内存中的Map,然后将内存中的Map写进XML文件中。使用上面的方式commit,由于sp.edit()又重新返回了一个新的Editor对象,缓存中的Map是空的,导致数据无法被存储。
4.2 取数据
步骤如下:
(1)获取SharedPreferences实例。
(2)读取单一数据:调用SharedPreferences的getXxx()方法,分别读取String,int,long等类型。
(3)读取全量数据:调用SharedPreferences的getAll()方法,再遍历map。
示例代码如下:

SharedPreferences sp = getSharedPreferences("MY_SP", Context.MODE_PRIVATE);String name = sp.getString("NAME", null);int age = sp.getInt("AGE", 0);

六、保存与读取图片demo

package demo.sp;  import java.io.ByteArrayInputStream;  import java.io.ByteArrayOutputStream;  import android.os.Bundle;  import android.util.Base64;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;  import android.widget.ImageView;  import android.app.Activity;  import android.content.Context;  import android.content.SharedPreferences;  import android.content.SharedPreferences.Editor;  import android.graphics.Bitmap;  import android.graphics.Bitmap.CompressFormat;  import android.graphics.BitmapFactory;  public class MainActivity extends Activity {      private Button mSaveButton;      private Button mGetButton;      private ImageView mImageView;      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);          init();      }      private void init(){          mSaveButton=(Button) findViewById(R.id.saveButton);          mSaveButton.setOnClickListener(new OnClickListener() {              @Override              public void onClick(View view) {                  saveBitmapToSharedPreferences();              }          });          mGetButton=(Button) findViewById(R.id.getButton);          mGetButton.setOnClickListener(new OnClickListener() {              @Override              public void onClick(View view) {                  getBitmapFromSharedPreferences();              }          });          mImageView=(ImageView) findViewById(R.id.imageView);      }      private void saveBitmapToSharedPreferences(){          Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);          //第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream          ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();          bitmap.compress(CompressFormat.PNG, 80, byteArrayOutputStream);          //第二步:利用Base64将字节数组输出流中的数据转换成字符串String          byte[] byteArray=byteArrayOutputStream.toByteArray();          String imageString=new String(Base64.encodeToString(byteArray, Base64.DEFAULT));          //第三步:将String保持至SharedPreferences          SharedPreferences sharedPreferences=getSharedPreferences("testSP", Context.MODE_PRIVATE);          Editor editor=sharedPreferences.edit();          editor.putString("image", imageString);          editor.commit();      }      private void getBitmapFromSharedPreferences(){          SharedPreferences sharedPreferences=getSharedPreferences("testSP", Context.MODE_PRIVATE);          //第一步:取出字符串形式的Bitmap          String imageString=sharedPreferences.getString("image", "");          //第二步:利用Base64将字符串转换为ByteArrayInputStream          byte[] byteArray=Base64.decode(imageString, Base64.DEFAULT);          ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArray);          //第三步:利用ByteArrayInputStream生成Bitmap          Bitmap bitmap=BitmapFactory.decodeStream(byteArrayInputStream);          mImageView.setImageBitmap(bitmap);      }    }

main.xml如下:

<RelativeLayout 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"     >      <Button          android:id="@+id/saveButton"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="保存图片到SharedPreferences"           android:layout_centerHorizontal="true"          android:layout_marginTop="25dip"/>       <Button          android:id="@+id/getButton"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="从SharedPreferences获取图片"           android:layout_centerHorizontal="true"          android:layout_marginTop="80dip"/>       <ImageView           android:id="@+id/imageView"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_centerInParent="true"          />  </RelativeLayout> 
原创粉丝点击