0
votes

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.

1
Please correct me if I'm wrong Is your issue finding a way to represent a database record in memory as a byte[], and to retrieve back the database record from the byte[] ??Ayesh Qumhieh
Correct, I'm looking for the best way to this. If there are any best practices or standard approaches to doing this with minimal transformation. Thanks.John

1 Answers

1
votes

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.