/**
* collection 里的类必须要implements Serializable,因为ObjectOutputStream的缘故
*/
public class SPUtils {
public static final String SP_NAME="needYourName";//您的SharedPreferences的名字
public static void setSPCollection(Context context, Collection collection, String collectionName) throws IOException {
SharedPreferences.Editor edit=getSharedPreferences(context, SP_NAME).edit();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(collection);
String string = new String(Base64.encode(byteArrayOutputStream.toByteArray(), Base64.DEFAULT));//利用Base64防止乱码
edit.putString(collectionName,string);
edit.apply();
objectOutputStream.close();
}
public static Collection getSPCollection(Context context, String collectionName) throws IOException, ClassNotFoundException {
String string = getSharedPreferences(context, SP_NAME).getString(collectionName, "");
if (TextUtils.isEmpty(string)||TextUtils.isEmpty(string.trim())){
return null;
}
byte[] decodeBytes = Base64.decode(string.getBytes(), Base64.DEFAULT);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decodeBytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Collection collection = (Collection) objectInputStream.readObject();
objectInputStream.close();
return collection;
}
public static SharedPreferences getSharedPreferences(Context context,String spName){
return context.getSharedPreferences(spName, Context.MODE_PRIVATE);
}
}
不懂可以提问,但或许度娘更适合你呢,开个玩笑,今天是大年初一,还敲代码,我也是醉了,实在是无聊的慌呀。
也记录一下,20岁快结束了,好好努力,加油。