基于一些小伙伴说在取出对象的时候出现null,这个问题可能是因为你的对象没有序列化的原因,如果存在内部类的也需要进行序列化。看下面的例子:
public class Test implements Serializable{
//内部类
public class Son implements Serializable{
//外部对象嵌套
private Son2 son;
}
}
//Son2类也需要进行序列化
public class Son2 implements Serializable{}
Son内部类或者Son2也需要进行序列化。
给大家分享一个小小的工具类,直接可以拷来用。有些什么不足的地方可以提一下意见哦。
版本1:
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public class SpUtil {
private static SharedPreferences sp;
private static SharedPreferences getSp(Context context) {
if (sp == null) {
sp = context.getSharedPreferences("SpUtil", Context.MODE_PRIVATE);
}
return sp;
}
/**
* 存入字符串
*
* @param context 上下文
* @param key 字符串的键
* @param value 字符串的值
*/
public static void putString(Context context, String key, String value) {
SharedPreferences preferences = getSp(context);
//存入数据
Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit();
}
/**
* 获取字符串
*
* @param context 上下文
* @param key 字符串的键
* @return 得到的字符串
*/
public static String getString(Context context, String key) {
SharedPreferences preferences = getSp(context);
return preferences.getString(key, "");
}
/**
* 获取字符串
*
* @param context 上下文
* @param key 字符串的键
* @param value 字符串的默认值
* @return 得到的字符串
*/
public static String getString(Context context, String key, String value) {
SharedPreferences preferences = getSp(context);
return preferences.getString(key, value);
}
/**
* 保存布尔值
*
* @param context 上下文
* @param key 键
* @param value 值
*/
public static void putBoolean(Context context, String key, boolean value) {
SharedPreferences sp = getSp(context);
Editor editor = sp.edit();
editor.putBoolean(key, value);
editor.commit();
}
/**
* 获取布尔值
*
* @param context 上下文
* @param key 键
* @param defValue 默认值
* @return 返回保存的值
*/
public static boolean getBoolean(Context context, String key, boolean defValue) {
SharedPreferences sp = getSp(context);
return sp.getBoolean(key, defValue);
}
/**
* 保存long值
*
* @param context 上下文
* @param key 键
* @param value 值
*/
public static void putLong(Context context, String key, long value) {
SharedPreferences sp = getSp(context);
Editor editor = sp.edit();
editor.putLong(key, value);
editor.commit();
}
/**
* 获取long值
*
* @param context 上下文
* @param key 键
* @param defValue 默认值
* @return 保存的值
*/
public static long getLong(Context context, String key, long defValue) {
SharedPreferences sp = getSp(context);
return sp.getLong(key, defValue);
}
/**
* 保存int值
*
* @param context 上下文
* @param key 键
* @param value 值
*/
public static void putInt(Context context, String key, int value) {
SharedPreferences sp = getSp(context);
Editor editor = sp.edit();
editor.putInt(key, value);
editor.commit();
}
/**
* 获取long值
*
* @param context 上下文
* @param key 键
* @param defValue 默认值
* @return 保存的值
*/
public static int getInt(Context context, String key, int defValue) {
SharedPreferences sp = getSp(context);
return sp.getInt(key, defValue);
}
/**
* 保存对象
*
* @param context 上下文
* @param key 键
* @param obj 要保存的对象(Serializable的子类)
* @param <T> 泛型定义
*/
public static <T extends Serializable> void putObject(Context context, String key, T obj) {
try {
put(context, key, obj);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取对象
*
* @param context 上下文
* @param key 键
* @param <T> 指定泛型
* @return 泛型对象
*/
public static <T extends Serializable> T getObject(Context context, String key) {
try {
return (T) get(context, key);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 存储List集合
* @param context 上下文
* @param key 存储的键
* @param list 存储的集合
*/
public static void putList(Context context, String key, List<? extends Serializable> list) {
try {
put(context, key, list);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取List集合
* @param context 上下文
* @param key 键
* @param <E> 指定泛型
* @return List集合
*/
public static <E extends Serializable> List<E> getList(Context context, String key) {
try {
return (List<E>) get(context, key);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 存储Map集合
* @param context 上下文
* @param key 键
* @param map 存储的集合
* @param <K> 指定Map的键
* @param <V> 指定Map的值
*/
public static <K extends Serializable, V extends Serializable> void putMap(Context context,
String key, Map<K, V> map)
{
try {
put(context, key, map);
} catch (Exception e) {
e.printStackTrace();
}
}
public static <K extends Serializable, V extends Serializable> Map<K, V> getMap(Context context,
String key)
{
try {
return (Map<K, V>) get(context, key);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**存储对象*/
private static void put(Context context, String key, Object obj)
throws IOException
{
if (obj == null) {//判断对象是否为空
return;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
// 将对象放到OutputStream中
// 将对象转换成byte数组,并将其进行base64编码
String objectStr = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
baos.close();
oos.close();
putString(context, key, objectStr);
}
/**获取对象*/
private static Object get(Context context, String key)
throws IOException, ClassNotFoundException
{
String wordBase64 = getString(context, key);
// 将base64格式字符串还原成byte数组
if (TextUtils.isEmpty(wordBase64)) { //不可少,否则在下面会报java.io.StreamCorruptedException
return null;
}
byte[] objBytes = Base64.decode(wordBase64.getBytes(), Base64.DEFAULT);
ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
ObjectInputStream ois = new ObjectInputStream(bais);
// 将byte数组转换成product对象
Object obj = ois.readObject();
bais.close();
ois.close();
return obj;
}
}
版本2:(由于Context传得太多,比较麻烦,进行了一些更改。这个工具类需要先调用init方法进行初始化,初始化的时候可以给定文件名称)
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**SharedPreferences工具类,需要先调用init进行初始化*/
public final class SpUtil {
private static SharedPreferences sp = null;
/**初始化SpUtil工具类
* @param application 用于获取上下文
* @param spName 设置SharedPreferences文件名(不用添加后缀),默认名称:SpUtil.xml*/
public static void init(@NonNull Application application, String spName) {
if (sp == null) {
sp = application.getApplicationContext().getSharedPreferences(
TextUtils.isEmpty(spName) ? "SpUtil" : spName, Context.MODE_PRIVATE);
}
}
/**
* 存入字符串
* @param key 字符串的键
* @param value 字符串的值
*/
@SuppressLint("ApplySharedPref")
public static void putString(String key, String value) {
//存入数据
Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
/**
* 获取字符串
* @param key 字符串的键
* @return 得到的字符串
*/
public static String getString(String key) {return getString(key, "");}
/**
* 获取字符串
* @param key 字符串的键
* @param defValue 字符串的默认值
* @return 得到的字符串
*/
public static String getString(String key, String defValue)
{return sp.getString(key, defValue);}
/**
* 保存布尔值
* @param key 键
* @param value 值
*/
@SuppressLint("ApplySharedPref")
public static void putBoolean(String key, boolean value) {
Editor editor = sp.edit();
editor.putBoolean(key, value);
editor.commit();
}
/**
* 获取布尔值
* @param key 键
* @param defValue 默认值
* @return 返回保存的值
*/
public static boolean getBoolean(String key, boolean defValue)
{return sp.getBoolean(key, defValue);}
/**
* 保存long值
* @param key 键
* @param value 值
*/
@SuppressLint("ApplySharedPref")
public static void putLong(String key, long value) {
Editor editor = sp.edit();
editor.putLong(key, value);
editor.commit();
}
/**
* 获取long值
* @param key 键
* @param defValue 默认值
* @return 保存的值
*/
public static long getLong(String key, long defValue) {return sp.getLong(key, defValue);}
/**
* 保存int值
* @param key 键
* @param value 值
*/
@SuppressLint("ApplySharedPref")
public static void putInt(String key, int value) {
Editor editor = sp.edit();
editor.putInt(key, value);
editor.commit();
}
/**
* 获取int值
* @param key 键
* @param defValue 默认值
* @return 保存的值
*/
public static int getInt(String key, int defValue) {return sp.getInt(key, defValue);}
/**
* 保存对象
* @param key 键
* @param obj 要保存的对象(Serializable的子类)
* @param <T> 泛型定义
*/
public static <T extends Serializable> void putObject(String key, T obj)
{
if (obj == null) {
putString(key, "");
return;
}
putString(key, obj2Base64(obj));
}
/**
* 获取对象
* @param key 键
* @param <T> 指定泛型
* @return 泛型对象
*/
@Nullable
public static <T extends Serializable> T getObject(String key)
{ return base64ToObj(getString(key));}
/**
* 存储List集合
* @param key 存储的键
* @param list 存储的集合
*/
public static void putList(String key, List<? extends Serializable> list)
{putString(key, obj2Base64(list));}
/**
* 获取List集合
* @param key 键
* @param <E> 指定泛型
* @return List集合
*/
@Nullable
public static <E extends Serializable> List<E> getList(String key)
{return (List<E>) base64ToObj(getString(key));}
/**
* 存储Map集合
* @param key 键
* @param map 存储的集合
* @param <K> 指定Map的键
* @param <V> 指定Map的值
*/
public static <K extends Serializable, V> void putMap(String key, Map<K, V> map)
{putString(key, obj2Base64(map));}
/**
* 获取map集合
* @param key 键
* @param <K> 指定Map的键
* @param <V> 指定Map的值
* @return 存储的集合
*/
@Nullable
public static <K extends Serializable, V> Map<K, V> getMap(String key)
{return (Map<K, V>) base64ToObj(getString(key));}
/**
* 对象转字符串
* @param obj 任意对象
* @return base64字符串
*/
private static String obj2Base64(Object obj) {
//判断对象是否为空
if (obj == null) {return null;}
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
String objectStr = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
// 将对象放到OutputStream中
// 将对象转换成byte数组,并将其进行base64编码
objectStr = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
} catch (Exception e) {e.printStackTrace();} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {e.printStackTrace();}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {e.printStackTrace();}
}
}
return objectStr;
}
/**
* base64转对象
* @param base64 字符串
* @param <T> 指定转成的类型
* @return 指定类型对象 失败返回null
*/
private static <T> T base64ToObj(String base64) {
// 将base64格式字符串还原成byte数组
if (TextUtils.isEmpty(base64)) {return null;}
byte[] objBytes = Base64.decode(base64.getBytes(), Base64.DEFAULT);
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
T t = null;
try {
bais = new ByteArrayInputStream(objBytes);
ois = new ObjectInputStream(bais);
t = (T) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {e.printStackTrace();}
}
if (ois != null) {
try {
ois.close();
} catch (IOException e) {e.printStackTrace();}
}
}
return t;
}
/**
* 移除字符串
* @param key 字符串的键
*/
public static void removeByKey(String key) {
Editor editor = sp.edit();
editor.remove(key);
editor.apply();
}
}
有疑问可以发邮件到我邮箱:binary_56@foxmail.com
转载时请标明出处,谢谢!