Sharedprefernces的使用总结?

    在Android存储数据的方式有多种如文件、sqlite、contentprivder、Sharedprefernces等方式,一般我们的数据都会选择使用Sharedprefernces来保存,因为使用最方便,不仅可以保存常用的String、int、boolean数据类型的数据,也可以保存对象,集合,图片。

     1.基本的Sharedprefernces保存数据的用法

1 SharedPreferences prefe = content.getSharedPreferences(KEY_USERS_PHOTO,0);
2 Editor editor = prefe.edit();
3 editor.putBoolean("islogin",isloginSucess);
4 editor.commit();

     2.Sharedprefernces获取保存数据的方法

1 SharedPreferences prefe = content.getSharedPreferences(KEY_USERS_PHOTO,0);
2         boolean isLoginSucess = prefe.getBoolean("islogin",false);
3         return isLoginSucess;

   这是最基本的boolean类型的保存,String,int也是一样的方式,我们讲了Sharedprefernces不仅可以保存简单的字符串信息,也可以保存对象,接下来我们看下如何用Sharedprefernces来保存对象,

    3.Sharedprefernces保存数据对象的使用

 1 /**
 2      * 存储一个对象
 3      * 
 4      * @param context
 5      * @param
 6      * @param key
 7      */
 8     public static <T> void saveObj(Context context, T obj, String key) {
 9         T _obj = obj;
10 
11         SharedPreferences prefe = context.getSharedPreferences(PREFERNCE_FILE_NAME, 0);
12         // 创建字节输出流
13         ByteArrayOutputStream baos = new ByteArrayOutputStream();
14         try {
15             // 创建对象输出流,封装字节流
16             ObjectOutputStream oos = new ObjectOutputStream(baos);
17             // 将对象写入字节流
18             oos.writeObject(_obj);
19             // 将字节流编码成base64的字符串
20 //            String list_base64 = new String(Base64.encodeBase64(baos.toByteArray()));
21             String list_base64 = new String(Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));
22             Editor editor = prefe.edit();
23             editor.putString(key, list_base64);
24             editor.commit();
25             LogUtil.i(TAG, "保存obj成功");
26         } catch (Exception e) {
27             e.printStackTrace();
28             LogUtil.i(TAG, "保存obj失败");
29         }
30     }

    这里我们提供一个保存对象的方法,从方法中我们看到,它主要是通过ByteArrayOutputStream把数据转换为字节流,在把对象写入字节流在通过base64.encodeToString转化为base64的字符串来保

    4.SharedPreferences读取保存的对象方式

 1 /**
 2      * @param context
 3      * @return
 4      */
 5     public static Object readObj(Context context, String key) {
 6         Object obj = null;
 7         SharedPreferences prefe = context.getSharedPreferences(PREFERNCE_FILE_NAME, 0);
 8         String replysBase64 = prefe.getString(key, "");
 9         if (TextUtils.isEmpty(replysBase64)) {
10             return obj;
11         }
12         // 读取字节
13 //        byte[] base64 = Base64.decodeBase64(replysBase64.getBytes());
14         byte[] base64 = Base64.decode(replysBase64.getBytes(),Base64.DEFAULT);
15         // 封装到字节读取流
16         ByteArrayInputStream bais = new ByteArrayInputStream(base64);
17         try {
18             // 封装到对象读取流
19             ObjectInputStream ois = new ObjectInputStream(bais);
20             try {
21                 // 读取对象
22                 obj = ois.readObject();
23             } catch (ClassNotFoundException e) {
24                 e.printStackTrace();
25             }
26         } catch (StreamCorruptedException e) {
27             e.printStackTrace();
28         } catch (IOException e) {
29             e.printStackTrace();
30         }
31 
32         return obj;
33     }

     主要是把获取到的base64字符串转换字节流在同构读取字节流转化为对象。

    5.SharedPrefences保存图片的方式?

1 public static void saveUsersPhoto(Context context,String basestring){
2         SharedPreferences prefe = context.getSharedPreferences(KEY_USERS_PHOTO, 0);
3         Editor editor = prefe.edit();
4         editor.putString("usersimage",basestring);
5         editor.commit();
6     }

主要是把图片bitmap转换为base64的字符串的方式,然后以字符串的方式进行保存。

   6.SharedPrefences获取图片的方式?

1 SharedPreferences prefe = content.getSharedPreferences(KEY_USERS_PHOTO,0);
2         String basestirng = prefe.getString("usersimage", "");
3         //第二步:利用Base64将字符串转换为ByteArrayInputStream
4         byte[] byteArray=Base64.decode(basestirng, Base64.DEFAULT);
5         ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArray);
6         //第三步:利用ByteArrayInputStream生成Bitmap
7         Bitmap bitmap= BitmapFactory.decodeStream(byteArrayInputStream);
8         return bitmap;

主要是通过把base64字符串通过Base64.decode转换为字节流,在通过转化为ByteArrayInputStream在通过BitmapFactory.decodeStream()转化为bitmap返回。

7.保存集合/获取集合数据

 1 保存集合数据
 2 public static void saveCollectionInfo(Context context, List<Object> list){
 3         saveObj(context, list, KEY_COLLECTION_INFO);
 4     }
 5 
 6 
 7 获取集合数据
 8 public static List<Object> getCollectionInfo(Context context){
 9         return (List<Object>) readObj(context, KEY_COLLECTION_INFO);
10     }

最后对以上做一封装,这样可以使我们的整个app的都以使用不需要重复new出来

package com.info.mettingapp.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;
import com.info.mettingapp.model.UserModelBaseModel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.List;


/**
 * 缓存工具类
 * 
 * @author joe 2015年5月13日
 */
public class SharedpreferncesUtil {
    /** 数据全局的key */
    public static final String TAG="";
    public static final String PREFERNCE_FILE_NAME = ""; // 缓存文件名
    public static final String USER_GUIDE_FILE_NAME = "";   //引导界面文件名
    //-----key-----
    public static final String KEY_USER_INFO = "";
    //保存环信信息
    //----collection----
    public static final String KEY_COLLECTION_INFO = "";  //收藏文件名

    //保用用户上传的头像信息
    public static final String KEY_USERS_PHOTO="";

    
    /**
     * 保存用户信息
     * @param context
     * @param user
     */
    public static void saveUserModelBaseModelInfo(Context context, UserModelBaseModel user){
        saveObj(context, user, KEY_USER_INFO);
    }
    
    /**
     * 取出用户信息
     * @param context
     * @return
     */
    public static UserModelBaseModel getUserModelBaseModelInfo(Context context){
        return (UserModelBaseModel) readObj(context, KEY_USER_INFO);
    }

    /**
     * @param context
     * @return
     */
    public static Object readObj(Context context, String key) {
        Object obj = null;
        SharedPreferences prefe = context.getSharedPreferences(PREFERNCE_FILE_NAME, 0);
        String replysBase64 = prefe.getString(key, "");
        if (TextUtils.isEmpty(replysBase64)) {
            return obj;
        }
        // 读取字节
//        byte[] base64 = Base64.decodeBase64(replysBase64.getBytes());
        byte[] base64 = Base64.decode(replysBase64.getBytes(),Base64.DEFAULT);
        // 封装到字节读取流
        ByteArrayInputStream bais = new ByteArrayInputStream(base64);
        try {
            // 封装到对象读取流
            ObjectInputStream ois = new ObjectInputStream(bais);
            try {
                // 读取对象
                obj = ois.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return obj;
    }

    /**
     * 存储一个对象
     * 
     * @param context
     * @param
     * @param key
     */
    public static <T> void saveObj(Context context, T obj, String key) {
        T _obj = obj;

        SharedPreferences prefe = context.getSharedPreferences(PREFERNCE_FILE_NAME, 0);
        // 创建字节输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            // 创建对象输出流,封装字节流
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            // 将对象写入字节流
            oos.writeObject(_obj);
            // 将字节流编码成base64的字符串
//            String list_base64 = new String(Base64.encodeBase64(baos.toByteArray()));
            String list_base64 = new String(Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));
            Editor editor = prefe.edit();
            editor.putString(key, list_base64);
            editor.commit();
            LogUtil.i(TAG, "保存obj成功");
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.i(TAG, "保存obj失败");
        }
    }


    /**
     * 保存用户上传的头像
     */
    public static void saveUsersPhoto(Context context,String basestring){
        SharedPreferences prefe = context.getSharedPreferences(KEY_USERS_PHOTO, 0);
        Editor editor = prefe.edit();
        editor.putString("usersimage",basestring);
        editor.commit();
    }


    /**
     * 获取用户保存的头像
     */
    public static Bitmap getUsersSavePhoto(Context content){
        SharedPreferences prefe = content.getSharedPreferences(KEY_USERS_PHOTO,0);
        String basestirng = prefe.getString("usersimage", "");
        //第二步:利用Base64将字符串转换为ByteArrayInputStream
        byte[] byteArray=Base64.decode(basestirng, Base64.DEFAULT);
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArray);
        //第三步:利用ByteArrayInputStream生成Bitmap
        Bitmap bitmap= BitmapFactory.decodeStream(byteArrayInputStream);
        return bitmap;
    }/**
     * 保存收藏信息
     * @param context
     * @paramUserModelBaseModel
     */
    public static void saveCollectionInfo(Context context, List<Object> list){
        saveObj(context, list, KEY_COLLECTION_INFO);
    }
    
    /**
     * 取出收藏信息
     * @param context
     * @return
     */
    public static List<Object> getCollectionInfo(Context context){
        return (List<Object>) readObj(context, KEY_COLLECTION_INFO);
    }
    
    /**
     * 清除某个key对应的缓存
     * 
     * @param key
     * @param context
     */
    public static void clearByKey(String key, Context context) {
        SharedPreferences prefe = context.getSharedPreferences(PREFERNCE_FILE_NAME, 0);
        Editor editor = prefe.edit();
        editor.putString(key, "");
        editor.commit();
    }public static boolean getReadMode(Context context, String key, boolean defValue) {
        SharedPreferences prefe = context.getSharedPreferences(PREFERNCE_FILE_NAME, Context.MODE_PRIVATE);
        return prefe.getBoolean(key, defValue);
    }
    
    public static void putReadMode(Context context, String key, boolean state) {
        SharedPreferences prefe = context.getSharedPreferences(PREFERNCE_FILE_NAME, Context.MODE_PRIVATE);
        Editor editor = prefe.edit();
        editor.putBoolean(key, state);
        editor.commit();
    }
    
    public static int getFontSize(Context context, String key, int defValue) {
        SharedPreferences prefe = context.getSharedPreferences(PREFERNCE_FILE_NAME, Context.MODE_PRIVATE);
        return prefe.getInt(key, defValue);
    }
    
    public static void putFontSize(Context context, String key, int state) {
        SharedPreferences prefe = context.getSharedPreferences(PREFERNCE_FILE_NAME, Context.MODE_PRIVATE);
        Editor editor = prefe.edit();
        editor.putInt(key, state);
        editor.commit();
    }

}

 

posted @ 2016-05-12 17:14  android旅途  阅读(1429)  评论(0编辑  收藏  举报