开发者

How do you store the contents of a POJO in the preference store?

开发者 https://www.devze.com 2023-02-13 15:17 出处:网络
I am looking to find a way to store the value of a POJO (containing Strings, booleans, ints) in a preference variable that I can then retrieve by the key used when I store it.

I am looking to find a way to store the value of a POJO (containing Strings, booleans, ints) in a preference variable that I can then retrieve by the key used when I store it. The POJO contains many String / boolean / int attributes, so I don't want to store them each individually. The problem I'm running into is that the only preference variable types are String, boolean, float, and int. Is there so开发者_JS百科me way to convert the POJO to a String that I could then retrieve back per it's key and convert back to the POJO, sort of like casting it> 1) Populate the POJO 2) Convert the POJO to a String 3) Store the String in the preference Store with a key value (normal preference store stuff) 4) When needed, retrieve the data back from the preference store as a String and convert it back to the POJO.


Not the most elegant solution but:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(instance);
objectOutputStream.flush();
val = Base64.encodeBase64String(outputStream.toByteArray()));

To deserialise:

byte[] data = Base64.decodeBase64(dataStr);
ObjectInputStream objectInputStream = null;
try
{
     ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
     objectInputStream = new ObjectInputStream(inputStream);
     return (T)objectInputStream.readObject();
}
finally {
     if (objectInputStream != null)
        objectInputStream.close();
}

Where T is the object type.

0

精彩评论

暂无评论...
验证码 换一张
取 消