Monday, December 10, 2012

Android serialization of Objects ?


We can also see below links...
http://www.dreamincode.net/forums/topic/248522-serialization-in-android/

I'm going to go through the process of serializing and deserializing an object.

What this means is that we're going to convert an object into an array of bytes, which can easily be moved around or stored (for later use). And for deserialization we just take those bytes and convert them back into an Object.

The first one we have below is the serialization method, which just takes in a generic Object.


  public static byte[] serializeObject(Object o) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
      ObjectOutput out = new ObjectOutputStream(bos);
      out.writeObject(o);
      out.close();

      // Get the bytes of the serialized object
      byte[] buf = bos.toByteArray();

      return buf;
    } catch(IOException ioe) {
      Log.e("serializeObject", "error", ioe);

      return null;
    }
  }

The second one is the deserialization method, which takes in an array of bytes;


  public static Object deserializeObject(byte[] b) {
    try {
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
      Object object = in.readObject();
      in.close();

      return object;
    } catch(ClassNotFoundException cnfe) {
      Log.e("deserializeObject", "class not found error", cnfe);

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

      return null;
    }
  }

If you're wondering how to use these, well here is an example.


  public class Bla implements Serializable {
    public String blaDate;
    public String blaText;
  }
 
  Bla bla = new Bla();
 
  // assuming that both those serialize and deserialize methods are under the SerializerClass
  byte[] blaBytes = SerializerClass.serializeObject(bla);
 
  Bla deserializedBla = (Bla) SerializerClass.deserializeObject(blaBytes);

You've probably noticed that I implemented Serializable - you need this in order to serialize an object. Some of the built in objects already have this implemented - for example the ArrayList object.

When deserializing you need to cast it back to what the object was, since it's returning it as a generic Object - hence the (Bla).
Anyways, hope this helped someone, and if you noticed any mistakes, please let me know.

1 comment:

  1. One gets irritated when they face unexpected issues while bitcoin transaction in Binance. Such abrupt issues are unable to resolve and also put stop at the user’s works. In order to fix such issues, you can dial Binance support number +1877-330-7540 which is functional throughout the 365 days Binance Support NUmber in a year. The talented and nimble executives are at their best in providing commendable services to the users in minimal time.

    ReplyDelete