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

时间:2013-06-17 13:26:57

标签: android storage gesture

特别是,我想将一个给定的手势存储在设备的内存中。通常对于这些事情我使用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;
    }
}

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

2 个答案:

答案 0 :(得分:2)

我认为您可以序列化对象并返回。这样,您就可以在SharedPreferences和内部存储中使用它。

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

答案 1 :(得分:0)

查看Java的Serializable接口。您可以创建自己的实现Serializable的对象来挖掘手势,然后将该对象写入内部存储。 Here是在Android中使用序列化的链接。

相关问题