这是正确的吗。我有这个gridview
。我想将其项目保存为 sqlite 中的 blob。所以当我打开 sqlite 中的保存数据列表时,只需加载保存的数据items
并打电话adapter.notifyDataSetChanged
to my gridview
我尝试了这个,但我得到了NotSerializableException
error
列表项 = new ArrayList();
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch (IOException ioe) {
Log.e("serializeObject", "error", ioe);
return null;
}
}
我的插入行
public long insertRow(byte[] data) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATA, data);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
然后我插入序列化对象
myDB.insertRow(MyDBAdapter.serializeObject(items));
我也很困惑。我应该保存适配器还是项目列表?
我将数据以 BLOB 形式存储在数据库中的方式是将它们转换为 JSON,然后存储字节。
例如
ArrayList<Person> persons = new ArrayList<>();
Gson gson = new Gson();
ContentValues values = new ContentValues();
values.put(MyProvider.KEY_DATA, gson.toJson(persons).getBytes());
// insert or update the DB
并取回列表
byte[] blob = cursor.getBlob(cursor.getColumnIndex(MyProvider.KEY_DATA));
String json = new String(blob);
Gson gson = new Gson();
ArrayList<Person> persons = gson.fromJson(json, new TypeToken<ArrayList<Person>>()
{}.getType());
编辑:要回答你的最后一个问题,你应该存储你的数据(项目列表)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)