【问题标题】:Android Save object as blob in sqliteAndroid在sqlite中将对象保存为blob
【发布时间】:2014-06-27 23:21:55
【问题描述】:

是这样吗。我有这个gridview。我想将其项目保存为 sqlite 中的 blob。所以当我在 sqlite 中打开保存数据列表时,我只需加载保存 items 并将 adapter.notifyDataSetChanged 调用到我的 gridview

我试过这个但我收到NotSerializableException 错误

列表项 = 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));

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

【问题讨论】:

    标签: android sqlite gridview


    【解决方案1】:

    我将数据作为 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());
    

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

    【讨论】:

    • 什么意思?如何存储项目列表?或者如何让他们回来?
    • 编辑了答案以演示如何让他们回来:)
    • 由于数据是 json,将数据作为 blob 而不是文本保存到数据库有什么好处?问是因为我也将 json 存储到数据库中。
    • @Redshirt 这个问题已经很老了。我早就放弃了将 json 存储为 blob,因为它没有任何好处。话虽如此,问题是关于将对象保存为 BLOB,所以我没有修改我的答案。
    • 我得到------->(方法抛出'android.database.CursorIndexOutOfBoundsException'异常)在这个区域:cursor.getBlob(cursor.getColumnIndex(nameObject)
    【解决方案2】:

    不是(Object o),而是通过(Serializable o)。然后,在您传递的内容中,将implements Serializable 添加到类定义中。

    【讨论】:

      猜你喜欢
      • 2020-03-03
      • 2012-01-11
      • 1970-01-01
      • 2015-06-19
      • 2017-02-13
      • 2011-08-30
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多