MySharedpreference
来源:互联网 发布:中山大学网络服务中心 编辑:程序博客网 时间:2024/06/16 17:01
public class MySharedpreference { private static MySharedpreference instance; UserInfo userInfo = null; long startTime = 0l; long endTime = 0l; private Context mContext; private MySharedpreference(Context context) { mContext = context; } public static MySharedpreference getInstance(Context context) { if (instance == null) { synchronized (MySharedpreference.class) { if (instance == null) { instance = new MySharedpreference(context); } } } return instance; } public void saveObject(UserInfo userInfo) throws IOException { SharedPreferences sp =mContext.getSharedPreferences("userInfo", 0); SharedPreferences.Editor edit = sp.edit(); edit.putString("userInfo", serialize(userInfo)); edit.commit(); } public UserInfo getObject() throws IOException, ClassNotFoundException { SharedPreferences sp = mContext.getSharedPreferences("userInfo", 0); String userInfo = sp.getString("userInfo", null); if (userInfo==null){ System.out.println("获取的内容的长度为零"); return null; } return deSerialization(userInfo); } /** * 序列化对象 * * @param userInfo * @return * @throws IOException */ private String serialize(UserInfo userInfo) throws IOException { startTime = System.currentTimeMillis(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream( byteArrayOutputStream); objectOutputStream.writeObject(userInfo); String serStr = byteArrayOutputStream.toString("ISO-8859-1"); serStr = java.net.URLEncoder.encode(serStr, "UTF-8"); objectOutputStream.close(); byteArrayOutputStream.close(); Log.d("serial", "serialize str =" + serStr); endTime = System.currentTimeMillis(); Log.d("serial", "序列化耗时为:" + (endTime - startTime)); return serStr; } /** * 反序列化对象 * * @param str * @return * @throws IOException * @throws ClassNotFoundException */ private UserInfo deSerialization(String str) throws IOException, ClassNotFoundException { startTime = System.currentTimeMillis(); String redStr = java.net.URLDecoder.decode(str, "UTF-8"); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( redStr.getBytes("ISO-8859-1")); ObjectInputStream objectInputStream = new ObjectInputStream( byteArrayInputStream); UserInfo userInfo = (UserInfo) objectInputStream.readObject(); objectInputStream.close(); byteArrayInputStream.close(); endTime = System.currentTimeMillis(); Log.d("serial", "反序列化耗时为:" + (endTime - startTime)); return userInfo; }}
阅读全文
0 0