Using Xamarin Binary Serialization to Pass Data Objects Between Android Activities

RecursiveEnigma
TechDev Mix
Published in
2 min readFeb 5, 2015

On a recent Xamarin Android project we had to pass data objects from one Activity to another using Intent.PutExtra(…). This is easier said than done in Android. When you pass a data from one Activity to another, you have a few options at your disposal. For primitives, like strings and integers, this is quite easy, and you can just use one of the appropriate overloads provided by Intent.PutExtra. If you want to pass a complex object between Activities, things get a little more complicated.

You can create an object that implements the IParcelable interface’s WriteToParcel(…) method. A bit of a schlep and a little intrusive if you ask me.

Antoher option is to simply use the string overload of PutExtra, and serialize your object to JSON. In the end we preferred a variation of this option, and that is to serialize our objects to binary instead, and use the PutExtra overload that takes in a byte[] array. Because the object is short lived, and not persisted or served to external clients, we have the option to use binary serialization instead. Binary serialization is faster, and more compressed than JSON, saving on time and resources.

Adding a binary serialized parameter

intent.PutExtra("ParameterName", (Serialization.toBin obj))

Getting a binary serialized parameter


let binary = intent.Extras.GetByteArray “ParameterName”
(Serialization.fromBin<’t option> binary)

To serialize an object instance to binary

open System.IO
open System.Runtime.Serialization.Formatters.Binary
module Serialization =
let sysBinSerlzr = BinaryFormatter()
let toBin obj =
use stream = new MemoryStream()
try
sysBinSerlzr.Serialize(stream, obj)
stream.Position <- 0L
stream.ToArray()
finally
stream.Close()

let fromBin<’t> (binary: byte array) =
use stream = new MemoryStream(binary)
try
sysBinSerlzr.Deserialize(stream) :?> ‘t
finally
stream.Close()

Configuration
1. Android Version: 4.4.2 API 19
2. Xamarin Studio Version: 5.5.4
3. F# Version: 2.3.98.1

--

--