I'm trying to serialize an object from within it and deserialize it using this answer: Reliably convert any object to String and then back again
But I get StreamCorruptedException while deserializing.
java.io.StreamCorruptedException
W/System.err: at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:2065)
W/System.err: at java.io.ObjectInputStream.<init>(ObjectInputStream.java:371)
W/System.err: at ShoppingCart.load(ShoppingCart.java:154)
Here is the Class :
public class ShoppingCart implements Serializable {
ArrayList<Item> items ;
String token ;
transient Context context ;
public ShoppingCart(Context cntx){
context = cntx ;
items = new ArrayList<Item>();
SharedPreferences preferences = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
token = preferences.getString("login_token", null);
}
public void emptyCart(){
items = new ArrayList<Item>();
store();
System.gc();
}
public boolean addToCart(Item item){
boolean exists = false ;
for(int i = 0 ; i < items.size() ; i++){
if(items.get(i).productID.equals(item.productID)){
exists = true ;
return false ;
}
}
if(!exists)
items.add(item);
store();
return true ;
}
public void removeFromCart(Item item){
items.remove(item);
store();
}
public void store() {
SharedPreferences.Editor editor =
context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
// serialize the object
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(this);
so.flush();
String serializedObject = bo.toString();
editor.putString("stored_cart", serializedObject);
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
public ShoppingCart load() {
SharedPreferences preferences = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String serializedObject = preferences.getString("stored_cart", null);
ShoppingCart newCart = null ;
// deserialize the object
try {
byte b[] = serializedObject.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
newCart = (ShoppingCart) si.readObject();
newCart.context = context ;
} catch (Exception e) {
e.printStackTrace();
}
return newCart ;
}
}
I'm calling the load()
function like this:
cart = new ShoppingCart(getApplicationContext());
SharedPreferences preferences =
getApplicationContext().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
if(preferences.getString("stored_cart", null) != null) {
cart = cart.load();
Log.d("AppController","cart loaded");
}
Since the Context
is not serilizable, so I made it transient
.
What am I doing wrong ?