在Android中将对象保存为SQLite中的Blob类型

11

这样做对吗?我有一个gridview,我想将它的项目作为Blob保存在sqlite中。因此,当我打开保存在sqlite中的数据列表时,我只需加载保存的items并调用adapter.notifyDataSetChanged 到我的gridview

我尝试了这个方法,但是遇到了NotSerializableException 错误。

列表项=新数组列表();

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));

我很困惑,是应该保存适配器还是项目列表?

2个回答

28

我在数据库中将数据存储为 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());

编辑:为回答您的最后一个问题,您应该存储您的数据(项目列表)。


你的意思是什么?是要存储一个项目列表还是如何取回它们? - Chris Margonis
编辑了答案以演示如何将它们取回 :) - Chris Margonis
1
由于数据是json格式的,将其保存为blob而不是纯文本是否有任何好处?我问这个问题是因为我也要将json存储到数据库中。 - Redshirt
2
@Redshirt 嗯,这个问题很久了。我早就放弃将JSON存储为BLOB,因为它没有任何好处。话虽如此,这个问题是关于将对象保存为BLOB的,所以我没有修改我的答案。 - Chris Margonis
我在这个区域得到了一个异常:方法抛出了“android.database.CursorIndexOutOfBoundsException”异常。代码如下:cursor.getBlob(cursor.getColumnIndex(nameObject))。 - user3402040
我认为插入操作没有成功,我收到了“索引0请求”,但大小为0的错误提示。 - user3402040

0

不要传递 (Object o),而是传递 (Serializable o)。然后,在你传递的东西中,将 implements Serializable 添加到类定义中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接