问题描述
这是对的.我有这个 gridview
.我想将它的项目保存为 sqlite 中的 blob.因此,当我在 sqlite 中打开保存数据列表时,只需加载保存 items
并调用 adapter.notifyDataSetChanged
到我的 gridview
is this right. I have this gridview
. I want to save its item as blob in sqlite. so when i open the list of save data in sqlite ill just load the save items
and call adapter.notifyDataSetChanged
to my gridview
我试过这个,但我得到 NotSerializableException
错误
I tried this one but I get NotSerializableException
error
列表项 = new ArrayList();
List items = 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));
我也很困惑.我应该保存适配器还是项目列表?
also i'm confuse. should i save the adapter or the list of items'?
推荐答案
我将数据作为 BLOB 存储在我的数据库中的方式是将它们转换为 JSON,然后存储字节.例如
The way I store data as BLOB in my DB, is by converting them to JSON and then storing the bytes.e.g.
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());
要回答您的最后一个问题,您应该存储您的数据(项目列表).
to answer your last question, you should store your data (list of items).
这篇关于Android在sqlite中将对象另存为blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!