简体   繁体   中英

How to convert database rows into a byte array and back for a Saved Game snapshot using Google Play Games Services

The goal is to convert database rows into a Saved Game snapshot for Google Play Games Services, then retrieve those rows and insert them on a secondary device that would open the Saved Game snapshot.

I am able to save and retrieve snapshots to/from Google Play Games Service with basic string data, but how could I store database rows into a byte array (byte array is required to store snapshot data using Google Play Games Services) and back for a Saved Game snapshot? Thanks you.

Since you're asking for a way represent a database record in memory as a byte[]. If I was in your position, I would first do a simple modelling, by creating a java class which can represent the content of the data base record.

For example:

A database record: {id, firstName, lastName} I would simply create a java class as a model like this:

public class Contact {
    private long id;
    private String firstName;
    private String lastName;
// add getters and setters
}

Now when you do a database query and you have one or more records, you can create a new instance of this model for every record and set the content of the model instance from the records you have.

Contact contact = new Contact();
contact.setFirstName("The first name from the database record");
//And so on.

Now to convert a model instance into a byte[]

ByteArrayOutputStream arrOutStream = new ByteArrayOutputStream();
try {
    ObjectOutputStream out = new ObjectOutputStream(arrOutStream);
    out.writeObject(contact);
    byte[] bytes = arrOutStream.toByteArray();
} catch (IOException e) {
    e.printStackTrace();
}

And to read that object back from the byte[]

byte[] bytesToRead;
ByteArrayInputStream arrInStream = new ByteArrayInputStream(bytesToRead);
try {
    ObjectInputStream objectInStream = new ObjectInputStream(arrInStream);
    contact = (Contact) objectInStream.readObject();
} catch (Exception e) {
    e.printStackTrace();
}

Now since you have the model you can put it back into your database.

If you need to do this for multiple records from the database into a single byte[], you can simply create a new model that contains a list of contacts:

class Contacts {

    List<Contact> contactsList;
}

Instead of serializing every record into a byte[], you can just create one instance of the Contacts model, and add as much contacts inside, then do the serialization only once for the Contacts instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM