我正在尝试从sqlite db中反序列化一个类,这就是我序列化它的方式:
protected String serializeRule(){
String ruleSerialized = "";
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(this);
so.flush();
ruleSerialized = bo.toString();
} catch (Exception e) {
ruleSerialized ="";
}
return ruleSerialized;
}
存储到sqlite数据库中:
public void writeRule(){
String ruleSerialized = serializeRule();
if (ruleSerialized != null && !ruleSerialized.isEmpty() ){
DatabaseHelper mDbHelper = new DatabaseHelper(context);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(RuleContract.RuleEntry.COLUMN_NAME, ruleSerialized);
id = db.insert(RuleContract.RuleEntry.TABLE_NAME, null, values);
}
}
对其进行反序列化:
public static ArrayList<RuleBase> getRules(Context context){
ArrayList<RuleBase> ret = new ArrayList<RuleBase>();
DatabaseHelper mDbHelper = new DatabaseHelper(context);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] projection = {
RuleContract.RuleEntry._ID,
RuleContract.RuleEntry.COLUMN_NAME
};
Cursor c = db.query(
RuleContract.RuleEntry.TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
if(c.moveToFirst()){
do{
String column1 = c.getString(0);
String column2 = c.getString(1);
RuleBase r = getRule(column2);
ret.add(r);
}while(c.moveToNext());
}
c.close();
db.close();
return ret;
}
public static RuleBase getRule(String rules){
RuleBase obj = null;
try {
byte b[] = rules.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
obj = (RuleBase) si.readObject();
} catch (Exception e) {}
return obj;
}
当我打开一个新的ObjectInputStream(bi)时,我总是遇到StreamCorruptedException与sqlite或其他一些问题?