gpt4 book ai didi

java - 如何在 SQLite 中将 Bundle 放入 blob 列中?

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:20 24 4
gpt4 key购买 nike

我有这个 bundle :

Bundle bundle = new Bundle();
bundle.putString("u", mp); // String mp
bundle.putSerializable("m", mealplan); // String[7][6][4][5] mealplan
save.putExtra("b", bundle);

我需要将其放入 blob 列中,但我不知 Prop 体如何操作。

最佳答案

Bundle 对象支持 Parcel,但 Parcel.marshall() documentation说:

The data you retrieve here must not be placed in any kind of persistent storage (on local disk, across a network, etc). For that, you should use standard serialization or another kind of general serialization mechanism. The Parcel marshalled representation is highly optimized for local IPC, and as such does not attempt to maintain compatibility with data created in different versions of the platform.

最简单的序列化机制可能是 JSON,它是一种可读的文本格式。要创建 JSON 字符串,您必须构建 JSONObject/JSONArray 对象树:

// write
JSONObject json = new JSONObject();
json.put("u", mp);
JSONArray mealplan_json = new JSONArray();
mealplan_json.put(...); // fill arrays recursively
json.put("m", mealplan_json);
String text = json.toString();

// read
JSONObject json = new JSONObject(text);
mp = json.getString("u");
JSONArray mealplan_json = json.getJSONArray("m");
...

如果你想用二进制编码节省空间,你必须使用序列化,它支持基本类型和任何正确实现 java.io.Serializable 的对象。 :

// write
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(mp);
oos.writeObject(mealplan);
oos.close();
byte[] bytes = bos.toByteArray();

// read
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
mp = (String) ois.readObject();
mealplan = (String[][][][]) ois.readObject();

请注意,此二进制序列化不存储任何键名称(“u”、“m”),因此您必须确保应用的所有版本以相同的顺序写入和读取相同的对象。

如果您想拥有键/值结构,则必须实现自己的辅助函数,该函数在前面使用单独的键字符串写入值,并将任意数量的键/值对读取到映射中。或者,创建您自己的可序列化对象,其中包含所需的元素(并注意此类在您的应用程序的 future 版本中保持兼容):

class MealPlanData implements Serializable {
String u;
String[][][][] mp;
};

如果您只有一个 Bundle 对象并且不知道其结构,则必须手动处理键/值:

// write
oos.writeInt(bundle.size());
for (String key : bundle.keySet()) {
Object value = bundle.get(key);
oos.writeObject(key);
oos.writeObject(value);
}

// read
int size = ios.readInt();
Map<String, Object> map = new ArrayMap<String, Object>();
for (int i = 0; i < size; i++) {
String key = (String) ios.readObject();
Object value = ios.readObject();
map.put(key, value);
}

关于java - 如何在 SQLite 中将 Bundle 放入 blob 列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42742978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com