Skip to content

Instantly share code, notes, and snippets.

@aspyct
Created February 28, 2017 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspyct/3a51c6b990fe09dc3627fc69e319b16d to your computer and use it in GitHub Desktop.
Save aspyct/3a51c6b990fe09dc3627fc69e319b16d to your computer and use it in GitHub Desktop.
Android/Xamarin Bundle serialization
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Android.OS;
namespace Serialization
{
public static class BundleSerializationExtensions
{
public static void PutObject(this Bundle self, string key, object obj)
{
var formatter = new BinaryFormatter();
var stream = new MemoryStream();
formatter.Serialize(stream, obj);
var bytes = stream.ToArray();
self.PutByteArray(key, bytes);
}
public static T GetObject<T>(this Bundle self, string key)
where T : class
{
if (self == null)
{
return default(T);
}
var bytes = self.GetByteArray(key);
if (bytes == null) {
return default(T);
}
var formatter = new BinaryFormatter();
var stream = new MemoryStream(self.GetByteArray(key));
return formatter.Deserialize(stream) as T;
}
}
}
using Android.App;
using Android.Widget;
using Android.OS;
namespace Serialization
{
[Activity(Label = "Serialization", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
State state;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
state = savedInstanceState.GetObject<State>("state") ?? new State();
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += delegate { button.Text = $"{state.Count++} clicks!"; };
}
protected override void OnSaveInstanceState(Bundle outState)
{
base.OnSaveInstanceState(outState);
outState.PutObject("state", state);
}
}
}
using System;
namespace Serialization
{
[Serializable]
public class State
{
public int Count { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment