gpt4 book ai didi

android - 如何在数据存储器中存储非字符串对象?

转载 作者:行者123 更新时间:2023-11-29 00:29:07 26 4
gpt4 key购买 nike

特别是,我想将给定的手势存储在设备的内存中。通常对于这些我使用 SharedPreferences,但是由于手势不是原始数据类型,所以它在这里不起作用;我还研究了将它存储在内部存储中,这是我想要的,但是这里的代码:http://developer.android.com/guide/topics/data/data-storage.html建议这仅适用于字符串。

有没有一种方法可以轻松地将对象存储在设备内存中,或者我是否需要将对象转换为字符串,然后在读取文件时再转换回来?

Gesture mGesture;
SharedPreferences stored = getSharedPreferences("Shared Preferences", 0);
SharedPreferences.Editor editor = stored.edit();
byte[] storedGesture = serializeObject(mGesture);
String storedGestureString = new String(storedGesture);
editor.putString("Gesture Password", storedGestureString);
}

public static byte[] serializeObject(Object mObject){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try{
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(mObject);
out.close();

byte[] buf = bos.toByteArray();
return buf;

} catch (IOException ioe) {
Log.e("serialize object", "error", ioe);
return null;
}
}

有与我尝试序列化相关的代码,当我在创建手势后点击“确认”按钮时,应用程序崩溃了。 Confirm 按钮基本上运行此代码。

最佳答案

我认为您可以序列化对象并返回。这样您就可以将它与 SharedPreferences 和内部存储一起使用。

这是关于如何在 Java(以及 Android)中实现序列化的教程 - http://www.tutorialspoint.com/java/java_serialization.htm

关于android - 如何在数据存储器中存储非字符串对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17148618/

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